Laravel is one of the popular PHP Framework in USA and European Region. Here we have mentioned most frequently asked Laravel Interview Questions and Answers specially for freshers and experienced.


 

1. Does Laravel Support Caching?

Ans:

Yes, Its provides.

2. How To Use Delete Statement In Laravel?

Ans:

DB::delete('delete from users where id = ?', [1015]);

3. How To Use Update Statement In Laravel?

Ans:

DB::update('update users set city_id = 10 where id = ?', [1015]);

4. How To Use Insert Statement In Laravel?

Ans:

DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]);

5. How To Use Select Query In Laravel?

Ans:

$users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
foreach($users as $user){
}
}

6. How To Enable The Query Logging?

Ans:

DB::connection()->enableQueryLog();

7. How To Set Database Connection In Laravel?

Ans:

Database configuration file path is : config/database.php
Following are sample of database file :

'mysql' => [
'read' => [
'host' => 'localhost',
],
'write' => [
'host' => 'localhost'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],

8. What Are Bundles,reverse Routing And The Ioc Container ?

Ans:

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

9. Compare Laravel With Codeigniter?

Ans:

Laravel :

  • Laravel is a framework with expressive, elegant syntax
  • Development is enjoyable, creative experience
  • Laravel is built for latest version of PHP
  • It is more object oriented compared to CodeIgniter
  • Laravel community is still small, but it is growing very fast.

Codeigniter :

  • CodeIgniter is a powerful PHP framework
  • Simple and elegant toolkit to create full-featured web applications.
  • Codeigniter is an older more mature framework
  • It is less object oriented compared to Laravel.
  • Codeigniter community is large.

10. What Are The Feature Of Laravel 5.0?

Ans:

  • Method injection
  • Contracts
  • Route caching
  • Events object
  • Multiple file system
  • Authentication Scaffolding
  • dotenv – Environment Detection
  • Laravel Scheduler


 

11. Explain About Laravel Project?

Ans:

  • Laravel is one of the most popular PHP frameworks used for Web Development.
  • This framework is with expressive, elegant syntax.
  • It is based on model–view–controller (MVC) architectural pattern.

12. What Are Advantages Of Laravel?

Ans:

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel

13. What Is Laravel?

Ans:

  • Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites.
  • Laravel helps you create applications using simple, expressive syntax.

14. What Is System Requirement For Installation Of Laravel 5.2 (latest Version)?

Ans:

  • PHP >= 5.5.9
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

15. How To Install Laravel?

Ans:

  • We can install the Laravel in following ways.
  • Laravel Installer
  • Composer Create-Project

16. Is Laravel An Open Source?

Ans:

Yes, Download the framework and use as per your requirement

17. What Is Offical Website Url Of Laravel?

Ans:

laravel.com.

18. In Which Language It Was Written?

Ans:

PHP.

19. What Is Current Stable Version Of Laravel?

Ans:

Version 5.2.36 dated June 6, 2016

20. When Laravel Was Launched?

Ans:

June 2011




 

21. What Developed The Laravel?

Ans:

Taylor Otwell.

22. What Are System Requirement For Laravel 5.0?

Ans:

Following are system requirements:

  • PHP >= 5.4, PHP < 7
  • Mcrypt PHP Extension
  • OpenSSL PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

23. What is Laravel ?

Ans:

Laravel is free open source “PHP framework” based on MVC design pattern .
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

24. What are pros and cons of using Laravel Framework ?

Ans:

Pros of using laravel Framework

  • Laravel framework has in-built lightweight blade template engine to speed up compiling tasks, and create layouts with dynamic content easily.
  • Hassles code reusability.
  • Eloquent ORM with PHP active record implementation
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration

Cons of using laravel Framework

  • Development process requires you to work with standards and should have real understanding of programming
  • Laravel is new framework and composer is not so strong in compare to npm (for node.js), ruby gems and python pip.
  • Development in laravel is not so fast in compare to ruby on rails.
  • Laravel is lightweight so it has less inbuilt support in compare to django and rails. But this problem can be solved by integrating third party tools, but for large and very custom websites it may be a tedious task

25. Explain Events in laravel ?

Ans:

An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel events provides a simple observer implementation,that allowing you to subscribe and listen for various events/actions that occur in your application.
All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.

26. Explain validations in laravel?

Ans:

In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database. Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequeststraitwhich provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.

27. What are pros and cons of using Laravel Framework?

Ans:

Pros of using Laravel Framework

  1. Laravel framework has in-built lightweight blade template engine to speed up compiling task and create layouts with dynamic content easily.
  2. Hassles code reusability.
  3. Eloquent ORM with PHP active record implementation
  4. Built in command line tool “Artisan” for creating a code skeleton , database structure and build their migration

Cons of using laravel Framework

  1. Development process requires you to work with standards and should have real understanding of programming
  2. Laravel is new framework and composer is not so strong in compare to npm (for node.js), ruby gems and python pip.
  3. Development in laravel is not so fast in compare to ruby on rails.
  4. Laravel is lightweight so it has less inbuilt support in compare to django and rails. But this problem can be solved by integrating third party tools, but for large and very custom websites it may be a tedious task

28. Explain Events in laravel ?

Ans:

An event is an action or occurrence recognized by a program that may be handled by the program or code. Laravel events provides a simple observer implementation, that allowing you to subscribe and listen for various events/actions that occur in your application.
All Event classes are generally stored in the app/Events directory, while their listeners are stored in app/Listeners of your application.

29. Explain validations in laravel?

Ans:

In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database. Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.

30. How to install laravel via composer ?

Ans:

You can install Laravel via composer by running below command.

composer create-project laravel/laravel your-project-name version


 

31. List some features of laravel 5.0?

Ans:

  • Inbuilt CRSF (cross-site request forgery ) Protection.
  • Inbuilt paginations
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • IOC (Inverse of Control) Container Or service container.

32. What is PHP artisan. List out some artisan commands ?

Ans:

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisan command:-

  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan –versian
  • php artisan make model model_name
  • php artisan make controller controller_name

33. List some default packages provided by Laravel 5.4 ?

Ans:

Below are list of some official/ default packages provided by Laravel 5.4

  • Cashier
  • Envoy
  • Passport
  • Scout
  • Socialite

34. What are named routes in Laravel?

Ans:

Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Url’s more comfortably.
You can specify named routes by chaining the name method onto the route definition:

Route::get('user/profile', function () {
//
})->name('profile');

You can specify route names for controller actions:

Route::get(‘user/profile’, ‘UserController@showProfile’)->name(‘profile’);

Once you have assigned a name to your routes, you may use the route’s name when generating URLs or redirects via the global route function:

// Generating URLs…
$url = route(‘profile’);

// Generating Redirects…
return redirect()->route(‘profile’);

35. What is database migration. How to create migration via artisan ?

Ans:

Migrations are like version control for your database, that’s allow your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.
Use below commands to create migration data via artisan.
// creating Migration
php artisan make:migration create_users_table

36. What are service providers ?

Ans:

Service Providers are central place where all laravel application is bootstrapped . Your application as well all Laravel core services are also bootstrapped by service providers.
All service providers extend the Illuminate\Support\ServiceProvider class. Most service providers contain a register and a boot method. Within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.

37. Explain Laravel’s service container ?

Ans:

One of the most powerful feature of Laravel is its Service Container. It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel.
Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

38. What is composer ?

Ans:

Composer is a tool for managing dependency in PHP. It allows you to declare the libraries on which your project depends on and will manage (install/update) them for you.
Laravel utilizes Composer to manage its dependencies.

39. What is dependency injection in Laravel ?

Ans:

In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client’s state.[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.
source(https://en.wikipedia.org/wiki/Dependency_injection).
You can do dependency injection via Constructor, setter and property injection.

40. What are Laravel Contract’s ?

Ans:

Laravel’s Contracts are nothing but a set of interfaces that define the core services provided by the Laravel framework.



 

41. Explain Facades in Laravel ?

Ans:

Laravel Facades provides a static like an interface to classes that are available in the application’s service container. Laravel self-ships with many facades which provide access to almost all features of Laravel ’s. Laravel facades serve as “static proxies” to underlying classes in the service container and provide benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace. You can easily access a facade like so:

use Illuminate\Support\Facades\Cache;

Route::get(‘/cache’, function () {
return Cache::get(‘key’);
});

42. What are Laravel eloquent?

Ans:

Laravel’s Eloquent ORM is simple Active Record implementation for working with your database. Laravel provide many different ways to interact with your database, Eloquent is most notable of them. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
Below is sample usage for querying and inserting new records in Database with Eloquent.

// Querying or finding records from products table where tag is 'new'
$products= Product::where('tag','new');
// Inserting new record
$product =new Product;
$product->title="Iphone 7";
$product->price="$700";
$product->tag='iphone';
$product->save();

43. How to enable query log in Laravel ?

Ans:

Use the enableQueryLog method to enable query log in Laravel

DB::connection()->enableQueryLog(); 
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

44. What is reverse routing in Laravel?

Ans:

Laravel reverse routing is generating URL’s based on route declarations.Reverse routing makes your application so much more flexible.It defines a relationship between links and Laravel routes.When a link is created by using names of existing routes, appropriate Uri’s are created automatically by Laravel. Here is an example of reverse routing.
// route declaration
Route::get(‘login’, ‘users@login’);
Using reverse routing we can create a link to it and pass in any parameters that we have defined. Optional parameters, if not supplied, are removed from the generated link.
{{ HTML::link_to_action(‘users@login’) }}
It will automatically generates a Url like http://xyz.com/login in view.

45. How to turn off CRSF protection for specific route in Laravel?

Ans:

To turn off CRSF protection in Laravel add following codes in “app/Http/Middleware/VerifyCsrfToken.php”

//add an array of Routes to skip CSRF check
private $exceptUrls = ['controller/route1', 'controller/route2'];
//modify this function
public function handle($request, Closure $next) {
//add this condition foreach($this->exceptUrls as $route) {
if ($request->is($route)) {
return $next($request);
}
}
return parent::handle($request, $next);
}

46. What are traits in Laravel ?

Ans:

PHP Traits are simply a group of methods that you want include within another class. A Trait, like an abstract classes cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
Here is an example of trait.

trait Sharable {

public function share($item)
{
return ‘share this item’;
}

}
You could then include this Trait within other classes like this:

class Post {

use Sharable;

}

class Comment {

use Sharable;

}
Now if you were to create new objects out of these classes you would find that they both have the share() method available:
$post = new Post;
echo $post->share(”); // ‘share this item’

$comment = new Comment;
echo $comment->share(”); // ‘share this item’

47. Does Laravel support caching?

Ans:

Yes, Laravel supports popular caching backends like Memcached and Redis.
By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system.For large projects, it is recommended to use Memcached or Redis.

48. Explain Laravel’s Middleware?

Ans:

As the name suggests, Middleware acts as a middleman between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.
There are two types of Middleware in Laravel.
Global Middleware: will run on every HTTP request of the application.
Route Middleware: will be assigned to a specific route.

49. What is Lumen?

Ans:

Lumen is PHP micro-framework that built on Laravel’s top components.It is created by Taylor Otwell. It is perfect option for building Laravel based micro-services and fast REST API’s. It’s one of the fastest micro-frameworks available.
You can install Lumen using composer by running below command
composer create-project –prefer-dist laravel/lumen blog

50. Explain Bundles in Laravel?

Ans:

In Laravel, bundles are also called packages.Packages are the primary way to extend the functionality of Laravel. Packages might be anything from a great way to work with dates like Carbon, or an entire BDD testing framework like Behat.In Laravel, you can create your custom packages too.




 

51. How to use custom table in Laravel Modal ?

Ans:

You can use custom table in Laravel by overriding protected $table property of Eloquent.

Below is sample uses

class User extends Eloquent{
protected $table="my_user_table";

}

52. List types of relationships available in Laravel Eloquent?

Ans:

Below are types of relationships supported by Laravel Eloquent ORM.

  • One To One
  • One To Many
  • One To Many (Inverse)
  • Many To Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations

53. Why are migrations necessary?

Ans:

Migrations are necessary because:

  • Without migrations, database consistency when sharing an app is almost impossible, especially as more and more people collaborate on the web app.
  • Your production database needs to be synced as well.

54. Provide System requirements for installation of Laravel 5.4 ?

Ans:

In order to install laravel,make sure your server meets the following requirements:

  • PHP >= 5.6.4
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

55. List some Aggregates methods provided by query builder in Laravel ?

Ans:

  • count()
  • max()
  • min()
  • avg()
  • sum()

56. What is Laravel ?

Ans:

Laravel is free open source “PHP framework” based on MVC Design Pattern .
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

57. List some official packages provided by Laravel?

Ans:

  • Cashier
  • Envoy
  • Passport
  • Scout
  • Socialite

58. List out latest features of Laravel.

Ans:

  • Inbuilt CRSF (cross-site request forgery) Protection.
  • Inbuilt paginations
  • Reverse Routing
  • Query builder
  • Route caching
  • Database Migration
  • IOC (Inverse of Control) Container Or service container.

59. List out some benefits of Laravel over other Php frameworks.

Ans:

  • Setup and customization process is easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.

60. What is composer ?

Ans:

Composer is PHP dependency manager used for installing dependencies of PHP applications.


 

61. How to install laravel via composer ?

Ans:

composer create-project laravel/laravel your-project-name version

62.How to check laravel current version ?

Ans:

You can check the current version of your Laravel installation using the –version option of artisan command
Usages:-
php artisan –version

63. What is php artisan. List out some artisan command ?

Ans:

PHPartisanis the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command:-

  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan –versian
  • php artisan make modal modal_name
  • php artisan make controller controller_name

64. Explain Events in laravel ?

Ans:

An event is anincident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation,that allow us to subscribe and listen for events in our application.
Below are some events examples in laravel :-

  • A new user has registered
  • A new comment is posted
  • User login/logout
  • New product is added.

65. How to enable query log in laravel?

Ans:

Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

66. How to turn off CRSF protection for a route in Laravel?

Ans:

In “app/Http/Middleware/VerifyCsrfToken.php”
//add an array of Routes to skip CSRF check

private $exceptUrls = [‘controller/route1’, ‘controller/route2’];

//modify this function

public function handle($request, Closure $next)
{
//add this condition
foreach($this->exceptUrls as $route) {
if ($request->is($route)) {
return $next($request);
}
}
return parent::handle($request, $next);
}

67. What is Lumen?

Ans:

Lumen is PHP micro framework that built on Laravel’s top components. It is created by Taylor Otwell. It is perfect option for building Laravel based micro-services and fast REST API’s. It’s one of the fastest micro-frameworks available.

68. What are laravel Contracts?

Ans:

Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravel framework.

69. Explain Laravel service container ?

Ans:

One of the most powerful feature of Laravel is its Service Container
It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel .
Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

70. How can you get users IP address in Laravel ?

Ans:

public function getUserIp(Request $request){
// Getting ip address of remote user
return $user_ip_address=$request->ip();
}


 

71. How to use custom table in Laravel Modal ?

Ans:

We can use custom table in laravel by overriding protected $table property of Eloquent. Below is sample uses

class User extends Eloquent{
protected $table="my_user_table";

}

72. What is Laravel Eloquent?

Ans:

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

rotected $table=”my_user_table”;
}

73. How to define Fillable Attribute in Laravel Modal ?

Ans:

You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

Class User extends Eloquent{
protected $fillable =array(‘id’,’first_name’,’last_name’,’age’);
}

74. What is in vendor directory of Laravel ?

Ans:

Any packages we pulled from composer is kept in vendor directory of laravel.

75. In which directory controllers are located in Laravel ?

Ans:

We kept all controllers in
app/http/Controllersdirectory

76. What does PHP compact function do ?

Ans:

PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.

77. Define ORM ?

Ans:

Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

78. How to create a record in Laravel using eloquent? ?

Ans:

To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage
public function saveProduct(Request $request )
$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();

79. List some Aggregates methods provided by query builder in Laravel

Ans:

  • count()
  • max()
  • min()
  • avg()
  • sum()

80. What is the purpose of the Eloquent cursor() method in laravel ?

Ans:

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage.
Example Usage

foreach (Product::where(‘name’, ‘bar’)->cursor() as $flight) {
//do some stuff
}



 

81. How to get Logged in user info in laravel ?

Ans:

Auth::User() function is used to get Logged in user info in laravel.
Usage:-

if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}

82. What are Closures in laravel ?

Ans:

Closures is an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.

83. What are Advantages of Laravel?

Ans:

  1. Easy and consistent syntax
  2. Set-up process is easy
  3. customization process is easy
  4. code is always regimented with Laravel

84. What are the feature of Laravel5.0?

Ans:

  1. Method injection
  2. Contracts
  3. Route caching
  4. Events object
  5. Multiple file system
  6. Authentication Scaffolding
  7. dotenv – Environmental Detection
  8. Laravel Scheduler

85. Compare Laravel with Codeigniter?

Ans:

Laravel

Codeigniter

Laravel is a framework with expressive, elegant syntax

CodeIgniter is a powerful PHP framework

Development is enjoyable, creative experience

Simple and elegant toolkit to create full-featured web applications.

Laravel is built for latest version of PHP

Codeigniter is an older more mature framework

It is more object oriented compared to CodeIgniter.

It is less object oriented compared to Laravel.

Laravel community is still small, but it is growing very fast.

Codeigniter community is large.

86. What are Bundles,Reverse Routing and The IoC container ?

Ans:

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

87. How to set Database connection in Laravel?

Ans:

Database configuration file path is : config/database.php
Following are sample of database file

‘mysql’ => [
‘read’ => [
‘host’ => ‘localhost’,
],
‘write’ => [
‘host’ => ‘localhost’
],
‘driver’ => ‘mysql’,
‘database’ => ‘database’,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
],

88. How to enable the Query Logging?

Ans:

DB::connection()->enableQueryLog();

89. How to use select query in Laravel?

Ans:

$users = DB::select(‘select * from users where city_id = ?’, 10);
if(!empty($users)){
foreach($users as $user){
}
}

90. How to use Insert Statement in Laravel?

Ans:

DB::insert(‘insert into users (id, name, city_id) values (?, ?)’, [1, ‘Web technology’,10]);

 

91. How to use Update Statement in Laravel?

Ans:

DB::update(‘update users set city_id = 10 where id = ?’, [1015]);

92. How to use Update Statement in Laravel?

Ans:

DB::update(‘update users set city_id = 10 where id = ?’, [1015]);

93. How to use delete Statement in Laravel?

Ans:

DB::delete(‘delete from users where id = ?’, [1015]);

94. Does Laravel support caching?

Ans:

Yes, Its provides.

95. What is HTTP middleware?

Ans:

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.

96. What is database migration? And how to use it to add insert initial data to database?

Ans:

Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.
Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

97. What directories that need to be writable laravel installation?

Ans:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

98. How to implement you own package in Laravel?

Ans:

You can create a package in laravel using the following steps:
1. Package folder and name
2. Composer.json file for the package
3. Loading package via main composer.json and PSR-4
4. Creating a Service Provider
5. Create a Controller for your package
6. Create our Routes.php file

99. What are the main differences between Laravel 4 and Laravel 5.x?

Ans:

Summarizing Laravel 5.0 Release notes from the above article:
1. The old app/models directory has been entirely removed.
2. Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory.
3. A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x.
4. Application language files and views have been moved to the resources directory.
5. All major Laravel components implement interfaces which are located in the illuminate/contracts repository.
6. New route:cache Artisan command to drastically speed up the registration of your routes.
7. Laravel 5 now supports HTTP middleware, and the included authentication and CSRF “filters” have been converted to middleware.
8. you may now type-hint dependencies on controller methods.
9. User registration, authentication, and password reset controllers are now included out of the box, as well as simple corresponding views, which are located at resources/views/auth.
10. You may now define events as objects instead of simply using strings.
11. In addition to the queue job format supported in Laravel 4, Laravel 5 allows you to represent your queued jobs as simple command objects. These commands live in the app/Commands directory.
12. A database queue driver is now included in Laravel, providing a simple, local queue driver that requires no extra package installation beyond your database software.
13. Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
14. The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP.
15. Laravel 5 now utilizes DotEnv by Vance Lucas.
16. Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets.
17. Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers.
18. Laravel now includes the powerful Flysystem filesystem abstraction library, providing pain free integration with local, Amazon S3, and Rackspace cloud storage – all with one, unified and elegant API!
19. Laravel 5.0 introduces form requests, which extend the Illuminate\Foundation\Http\FormRequest class. These request objects can be combined with controller method injection to provide a boiler-plate free method of validating user input.
20. The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests.
21. new Artisan generator commands have been added to the framework.
22. The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.

100. What is routing and how, and what are the different ways to write it?

Ans:

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group. For most applications, you will begin by defining routes in your routes/web.php file.



 

101. What is Laravel Framework?

Ans:

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern.

102. What are the main differences between Laravel 4 and Laravel 5.x?

Ans:

Summarizing Laravel 5.0 Release notes from the above article:

1. The old app/models directory has been entirely removed.
2. Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory.
3. A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x.
4. Application language files and views have been moved to the resources directory.
5. All major Laravel components implement interfaces which are located in the illuminate/contracts repository.
6. New route:cache Artisan command to drastically speed up the registration of your routes.
7. Laravel 5 now supports HTTP middleware, and the included authentication and CSRF “filters” have been converted to middleware.
8. you may now type-hint dependencies on controller methods.
9. User registration, authentication, and password reset controllers are now included out of the box, as well as simple corresponding views, which are located at resources/views/auth.
10. You may now define events as objects instead of simply using strings.
11. In addition to the queue job format supported in Laravel 4, Laravel 5 allows you to represent your queued jobs as simple command objects. These commands live in the app/Commands directory.
12. A database queue driver is now included in Laravel, providing a simple, local queue driver that requires no extra package installation beyond your database software.
13. Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
14. The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP.
15. Laravel 5 now utilizes DotEnv by Vance Lucas.
16. Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets.
17. Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers.
18. Laravel now includes the powerful Flysystem filesystem abstraction library, providing pain free integration with local, Amazon S3, and Rackspace cloud storage – all with one, unified and elegant API!
19. Laravel 5.0 introduces form requests, which extend the Illuminate\Foundation\Http\FormRequest class. These request objects can be combined with controller method injection to provide a boiler-plate free method of validating user input.
20. The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests.
21. new Artisan generator commands have been added to the framework.
22. The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.

103. What is routing and how, and what are the different ways to write it?

Ans:

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group. For most applications, you will begin by defining routes in your routes/web.php file.

104. What is Composer?

Ans:

Composer is a dependency manager for PHP. Composer will manage the dependencies you require on a project by project basis. This means that Composer will pull in all the required libraries, dependencies and manage them all in one place

105. What is Laravel Eloquent?

Ans:

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

106. What is Luman?

Ans:

Lumen is a new project from Laravel creator Taylor Otwell. It’s a “micro-framework”, meaning it’s a smaller, faster, leaner version of a full web application framework. It competes other popular micro-frameworks, Slim and Silex.

107. How to implement you own package in Laravel?

Ans:

You can create a package in laravel using the following steps:
1. Package folder and name
2. Composer.json file for the package
3. Loading package via main composer.json and PSR-4
4. Creating a Service Provider
5. Create a Controller for your package
6. Create our Routes.php file

108. What is database migration? And how to use it to add insert initial data to database?

Ans:

Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.
Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

109. What directories that need to be writable laravel installation?

Ans:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

110. What is HTTP middleware?

Ans:

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.




 

111. What is Laravel

Ans:

Laravel is free open source “PHP framework” based on MVC Design Pattern.
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

112. List some official packages provided by Laravel

Ans:

Below are some official packages provided by Laravel

Cashier :Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription “quantities”, cancellation grace periods, and even generate invoice PDFs.
Envoy :Laravel Envoy provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems.
Passport :Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Alex Bilbie.
Scout :Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.
Socialite :Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket. It handles almost all of the boilerplate social authentication code you are dreading writing.

113. What is Lumen?

Ans:

Lumen is PHP micro framework that built on Laravel’s top components. It is created by Taylor Otwell.
It is the perfect option for building Laravel based micro-services and fast REST API’s.
It’s one of the fastest micro-frameworks available.

114. List out some benefits of Laravel over other Php frameworks ?

Ans:

Top benifits of laravel framework

  • Setup and customization process is easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.

115. List out some latest features of Laravel Framework

Ans:

  • Inbuilt CRSF (cross-site request forgery ) Protection.
  • Laravel provided an easy way to protect your website from cross-site request forgery (CSRF) attacks.
  • Cross-site request forgeries are malicious attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.
  • Inbuilt paginations Laravel provides an easy approach to implement paginations in your application.Laravel’s paginator is integrated with the query builder and Eloquent ORM and
  • provides convenient, easy-to-use pagination of database.
  • Reverse Routing
  • In Laravel reverse routing is generating URL’s based on route declarations.Reverse routing makes your application so much more flexible.
  • Query builder:
  • Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.
  • The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
  • Route caching
  • Database Migration
  • IOC (Inverse of Control) Container Or service container.

116. What is composer ?

Ans:

Composer is PHP dependency manager used for installing dependencies of PHP applications.
It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel over and over, we can instead download popular packages.

117. How to install Laravel via composer ?

Ans:

To install Laravel with composer run below command on your terminal.

composer create-project Laravel/Laravel your-project-name version

118. What is php artisan. List out some artisan commands ?

Ans:

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command.

  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan –versian
  • php artisan make model model_name
  • php artisan make controller controller_name

119. How to check current installed version of Laravel ?

Ans:

Use php artisan –version command to check current installed version of Laravel Framework
Usage:

php artisan --version

120. List some Aggregates methods provided by query builder in Laravel ?

Ans:

Aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list
Below is list of some Aggregates methods provided by Laravel query builder.
count()
Usage:$products = DB::table(‘products’)->count();
max()
Usage:$price = DB::table(‘orders’)->max(‘price’);
min()
Usage:$price = DB::table(‘orders’)->min(‘price’);
avg()
Usage:$price = DB::table(‘orders’)->avg(‘price’);
sum()
Usage: $price = DB::table(‘orders’)->sum(‘price’);


 

121. Explain Events in Laravel ?

Ans:

what are laravel events
An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allow us to subscribe and listen for events in our application.An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allows us to subscribe and listen for events in our application.

Below are some events examples in Laravel:-

  • A new user has registered
  • A new comment is posted
  • User login/logout
  • New product is added.

122. How to turn off CRSF protection for a route in Laravel ?

Ans:

To turn off or diasble CRSF protection for specific routes in Laravel open “app/Http/Middleware/VerifyCsrfToken.php” file and add following code in it

//add this in your class
private $exceptUrls = ['controller/route1', 'controller/route2'];

//modify this function

public function handle($request, Closure $next)
{

//add this condition
foreach($this->exceptUrls as $route) {

if ($request->is($route)) {

return $next($request);

}

}
return parent::handle($request, $next);}

123. What happens when you type “php artisan” in the command line?

Ans:

When you type “PHP artisan” it lists of a few dozen different command options.

124. Which template engine Laravel use ?

Ans:

Laravel uses Blade Templating Engine.
Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

125. How can you change your default database type ?

Ans:

By default Laravel is configured to use MySQL.In order to change your default database edit your config/database.php and search for ‘default’ => ‘mysql’ and change it to whatever you want (like ‘default’ => ‘sqlite’).

126. Explain Migrations in Laravel ? How can you generate migration .

Ans:

what are laravel migrations
Laravel Migrations are like version control for your database, allowing a team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.

Steps to Generate Migrations in Laravel

  • To create a migration, use the make:migration Artisan command
  • When you create a migration file, Laravel stores it in /database/migrations directory.
  • Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.
  • Open the command prompt or terminal depending on your operating system.

127. What are service providers in laravel ?

Ans:

Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services are bootstrapped via service providers.
Service provider basically registers event listeners, middleware, routes to Laravel’s service container.
All service providers need to be registered in providers array of app/config.php file.

128. How do you register a Service Provider?

Ans:

To register a service provider follow below steps

  • Open to config/app.php
  • Find ‘providers’ array of the various ServiceProviders.
  • Add namespace ‘Iluminate\Abc\ABCServiceProvider:: class,’ to the end of the array.

129. What are Implicit Controllers ?

Ans:

Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route: controller method.
Usage :

Route::controller('base URI','');

130. What does “composer dump-autoload” do?

Ans:

Whenever we run “composer dump-autoload”
Composer re-reads the composer.json file to build up the list of files to autoload.



 

131. Explain Laravel service container ?

Ans:

One of the most powerful feature of Laravel is its Service Container .
It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel.
Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

132. How can you get users IP address in Laravel ?

Ans:

You can use request’s class ip() method to get IP address of user in Laravel.
Usage:

public function getUserIp(Request $request){
// Getting ip address of remote user
return $user_ip_address=$request->ip();

}

133. How to enable query log in Laravel?

Ans:

Use the enableQueryLog method: Use the enableQueryLog method:

DB::connection()->enableQueryLog();

You can get an array of the executed queries by using the getQueryLog method:

$queries = DB::getQueryLog();

134. What are Laravel Facades ?

Ans:

Laravel Facades provides a static like interface to classes that are available in the application’s service container.
Laravel self ships with many facades which provide access to almost all features of Laravel’s.
Laravel Facades serve as “static proxies” to underlying classes in the service container and provides benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the IlluminateSupportFacades namespace. You can easily access a Facade like so:

use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('key');
});

135. How to use custom table in Laravel Model ?

Ans:

We can use custom table in Laravel by overriding protected $table property of Eloquent. Below is sample uses

class User extends Eloquent{
protected $table="my_custom_table";

}

136. How can you define Fillable Attribute in a Laravel Model ?

Ans:

You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

Class User extends Eloquent{
protected $fillable =array('id','first_name','last_name','age');
}

137. What is the purpose of the Eloquent cursor() method in Laravel ?

Ans:

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage.
Example Usage

foreach (Product::where('name', 'bar')->cursor() as $flight) {

//do some stuff

}

138. What are Closures in laravel ?

Ans:

Closures are an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.

139. What is Kept in vendor directory of Laravel ?

Ans:

Any packages that are pulled from composer is kept in vendor directory of Laravel.

140. What are Laravel Contracts ?

Ans:

Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravelframework.
You can read about How to Laravel contracts by How to use Laravel facade




 

141. What does PHP compact function do ?

Ans:

compact() laravel
PHP compact function takes each key and tries to find a variable with that same name.If the variable is found, them it builds an associative array.

142. In which directory controllers are located in Laravel ?

Ans:

We kept all controllers in App/Http/Controllers directory

143. What is Kept in vendor directory of Laravel ?

Ans:

Any packages that are pulled from composer is kept in vendor directory of Laravel.

144. What are Laravel Contracts ?

Ans:

Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravelframework.
You can read about How to Laravel contracts by How to use Laravel facade

145. What are named routes in Laravel ?

Ans:

Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Url’s more comfortably.
You can specify named routes by chaining the name method onto the route definition:

Route::get('user/profile', function () {
//
})->name('profile');

You can specify route names for controller actions:

Route::get('user/profile', 'UserController@showProfile')->name('profile');

Once you have assigned a name to your routes, you may use the route’s name when generating URLs or redirects via the global route function:

// Generating URLs...
$url = route('profile');

// Generating Redirects…
return redirect()->route(‘profile’);

146. What are traits in Laravel ?

Ans:

what are laravel traits
Laravel Traits are simply a group of methods that you want include within another class. A Trait, like an abstract classes cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
Here is an example of trait.

trait Sharable {

public function share($item)
{
return ‘share this item’;
}

}

You could then include this Trait within other classes like this:

class Post {

use Sharable;

}

class Comment {

use Sharable;

}

Now if you were to create new objects out of these classes you would find that they both have the share() method available:

$post = new Post;
echo $post->share(''); // 'share this item'

$comment = new Comment;
echo $comment->share(”); // ‘share this item’

147. How to create migration via artisan ?

Ans:

Use below commands to create migration data via artisan.

// creating Migration
php artisan make:migration create_users_table

148. Explain validations in laravel?

Ans:

In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database. Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request.

149. Explain Laravel Eloquent

Ans:

Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP MAPPING).
It provides a beautiful, simple ActiveRecord implementation to work with your database.
In Eloquent each database table has the corresponding MODEL that is used to interact with table and perform a database related operation on the table.
Sample Model Class in Laravel.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{

}

150. Can laravel be hacked ?

Ans:

Answers to this question is NO.Laravel application’s are 100% secure (depends what you mean by “secure” as well), in terms of things you can do to prevent unwanted data/changes done without the user knowing.
Larevl have inbuilt CSRF security, input validations and encrypted session/cookies etc. Also, Laravel uses a high encryption level for securing Passwords.
With every update, there’s the possibility of new holes but you can keep up to date with Symfony changes and security issues on their site.


 

151. Does laravel support php 7

Ans:

Yes,laravel supports php 7

152. Define Active Record Implementation. How to use it Laravel ?

Ans:

Active Record Implementation is an architectural pattern found in software engineering that stores in-memory object data in relational databases. Active Record facilitates the creation and use of business objects whose data is required to persistent in the database. Laravel implements Active Records by Eloquent ORM. Below is sample usage of Active Records Implementation is Laravel.

$product = new Product;

$product->title = ‘Iphone 6s’;

$product->save();

Active Record style ORMs map an object to a database row. In the above example, we would be mapping the Product object to a row in the products table of database.

153. List Types of relationships supported by Laravel ?

Ans:

Laravel support 7 types of table relationships, they are

  • One To One
  • One To Many
  • One To Many (Inverse)
  • Many To Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations

154. Explain Laravel Query Builder ?

Ans:

Laravel’s database query builder provides a suitable, easy interface to creating and organization database queries. It can be used to achieve most database operations in our application and works on all supported database systems. The Laravel query planner uses PDO restriction necessary to keep our application against SQL injection attacks.

155. What is Laravel Elixir ?

Ans:

Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports common CSS and JavaScript preprocessors like Sass and Webpack. Using method chaining, Elixir allows you to fluently define your asset pipeline.

156. How to enable maintenance mode in Laravel 5 ?

Ans:

You can enable maintenance mode in Laravel 5, simply by executing below command.

 //To enable maintenance mode
php artisan down
//To disable maintenance mode
php artisan up

157. List out Databases Laravel supports ?

Ans:

Currently Laravel supports four major databases, they are :-

  • MySQL
  • Postgres
  • SQLite
  • SQL Server

158. How to get current environment in Laravel 5 ?

Ans:

You may access the current application environment via the environment method.

$environment = App::environment();
dd($environment);

159. What is the purpose of using dd() function iin laravel ?

Ans:

Laravel’s dd() is a helper function ,which will dump a variable’s contents to the browser and halt further script execution.

160. What is Method Spoofing in Laravel ?

Ans:

As HTML forms does not supports PUT, PATCH or DELETE request. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:


 

To generate the hidden input field _method, you may also use the method_field helper function:

 

In Blade template you can write it as below

{{ method_field('PUT') }}


 

161. What is the latest version of laravel?

Ans:

Laravel 5.5 is the latest version of Laravel. Here are steps to install and configure laravel 5.5

162. How to assign multiple middleware to Laravel route ?

Ans:

You can assign multiple middleware to Laravel route by using middleware method.
Example
// Assign multiple multiple middleware to Laravel to specific route

Route::get('/', function () {
//
})->middleware('firstMiddleware', 'secondMiddleware');

// Assign multiple multiple middleware to Laravel to route groups

Route::group(['middleware' => ['firstMiddleware','secondMiddleware']], function () {
//
});

163. How can you display HTML with Blade in laravel

Ans:

To display html in laravel you can use below synatax.

{!! $your_var !!}

164. What is Laravel?

Ans:

Laravel is free open source “PHP framework” based on MVC design pattern.
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

165. What are laravel facades?

Ans:

Laravel Facades provides a static like interface to classes that are available in the application’s service container. Laravel self ships with many facades which provide access to almost all features of Laravel’s .Laravel Facadesserve as “static proxies” to underlying classes in the service container and provides benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace. You can easily access a Facade like so:

use Illuminate\Support\Facades\Cache;
Route::get(‘/cache’, function () {
return Cache::get(‘key’);
});