Laravel interview questions and answers
Laravel interview questions and answers
1. What is Laravel?
Ans. Laravel is a free open source “PHP framework” based on the 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.
2.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.
3.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 Urls 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’);
4. 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.
5. 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’);
});
6. 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();
7. How to enable query log in Laravel ?
Ans. Use the enableQueryLog method to enable query log in LaravelDB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();
8. List some default packages provided by Laravel 5.6 ?
Ans.A.Below are a list of some official/ default packages provided by Laravel
Cashier
Envoy
Passport
Scout
Socialite
Horizon
9.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.
10. 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 usesclass User extends Eloquent{
protected $table=”my_user_table”;}
11.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.
12.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
13.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.
14.How to check request is ajax or not ?
Ans. In Laravel, we can use $request->ajax() method to check request is ajax or not.Example:public function saveData(Request $request)
{
if($request->ajax()){
return “Request is of Ajax Type”;
}
return “Request is of Http type”;
}
15. 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
16. How to extend login expire time in Auth?
Ans.You can extend the login expire time with config\session.php this file location. Just update lifetime the variables value. By default it is ‘lifetime’ => 120. According to your requirement update this variable.
17.What is middleware in Laravel?
Ans.In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.Example: If a user is not authenticated and it is trying to access the dashboard then, the middleware will redirect that user to the login page.Get ready to be answerable to this question. This is a favorite Laravel Interview Questions of many interviewers. Don’t let this question waste the opportunity. Read it twice.
18.What is Database Migration and how to use this in Laravel?
Ans. It is a type of version control for our database. It is allowing us to modify and share the application’s database schema easily.A migration file contains two methods up() and down().up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.
19. How to pass CSRF token with ajax request?
Ans.In between head, tag put <meta name=”csrf-token” content=”{{ csrf_token() }}”> and in Ajax, we have to add
$.ajaxSetup({
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
}
});up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.
20.How to get data between two dates in Laravel?
Ans.In Laravel, we can use whereBetween() function to get data between two dates.
Example
Blog::whereBetween(‘created_at’, [$dateOne, $dateTwo])->get();
21.How to turn off CSRF protection for a particular route in Laravel?
Ans.We can add that particular URL or Route in $except variable. It is present in the app\Http\Middleware\VerifyCsrfToken.php file.
Example
class VerifyCsrfToken extends BaseVerifier {
protected $except = [
‘Pass here your URL’,
];
}
22. What is the use of dd() in Laravel?
Ans. It is a helper function which is used to dump a variable’s contents to the browser and stop the further script execution. It stands for Dump and Die.
Example
dd($array);
23. What is PHP artisan in laravel? Name some common artisan commands?
Ans.Artisan is a type of the “command line interface” using in Laravel. It provides lots of helpful commands for you while developing your application. We can run these command according to our need.
Laravel supports various artisan commands like
php artisan list;
php artisan –version
php artisan down;
php artisan help;
php artisan up;
php artisan make:controller;
php artisan make:mail;
php artisan make:model;
php artisan make:migration;
php artisan make:middleware;
php artisan make:auth;
php artisan make:provider etc.;
24.What is the difference between {{ $username }} and {!! $username !!} in Laravel?
Ans. {{ $username }} is simply used to display text contents but {!! $username !!} is used to display content with HTML tags if exists.
25. How to use session in laravel?
Ans. 1. Retrieving Data from session
session()->get(‘key’);2. Retrieving All session data
session()->all();3. Remove data from session
session()->forget(‘key’); or session()->flush();4. Storing Data in session
session()->put(‘key’, ‘value’);
26.How to use mail() in laravel?
Ans.Laravel provides a powerful and clean API over the SwiftMailer library with drivers for Mailgun, SMTP, Amazon SES, SparkPost, and send an email. With this API, we can send email on a local server as well as the live server.
Here is an example through the mail()
Laravel allows us to store email messages in our views files. For example, to manage our emails, we can create an email directory within our resources/views directory.
Example
public function sendEmail(Request $request, $id)
{
$user = Admin::find($id);
Mail::send(’emails.reminder’, [‘user’ => $user], function ($m) use ($user) {
$m->from(‘info@bestinterviewquestion.com’, ‘Reminder’);
$m->to($user->email, $user->name)->subject(‘Your Reminder!’);
});
}
27. How to use cookies in laravel?
Ans.1. How to set Cookie
To set cookie value, we have to use Cookie::put(‘key’, ‘value’);
2. How to get Cookie
To get cookie Value we have to use Cookie::get(‘key’);
3. How to delete or remove Cookie
To remove cookie Value we have to use Cookie::forget(‘key’)
4. How to check Cookie
To Check cookie is exists or not, we have to use Cache::has(‘key’)
28. What is Auth? How is it used?
Ans.Laravel Auth is the process of identifying the user credentials with the database. Laravel managed it’s with the help of sessions which take input parameters like username and password, for user identification. If the settings match then the user is said to be authenticated.Auth is in-built functionality provided by Laravel; we have to configure.We can add this functionality with php artisan make: authAuth is used to identifying the user credentials with the database.
low web application
29. How to make a constant and use globally?
Ans. You can create a constants.php page in config folder if does not exist. Now you can put constant variable with value here and can use with Config::get(‘constants.VaribleName’);
Example
return [
‘ADMINEMAIL’ => ‘info@bestinterviewquestion.com’,
];
Now we can display with
Config::get(‘constants.ADMINEMAIL’);
30. What is with() in Laravel?
Ans. with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
31.How to get user’s ip address in laravel?
Ans. You can use request()->ip()You can also use : Request::ip() but in this case we have to call namespace like this : Use Illuminate\Http\Request;
32.What are the difference between softDelete() & delete() in Laravel?
Ans. 1. delete()
In case when we used to delete in Laravel then it removed records from the database table.
Example:
$delete = Post::where(‘id’, ‘=’, 1)->delete();
2. softDeletes()
To delete records permanently is not a good thing that’s why laravel used features are called SoftDelete. In this case, records did not remove from the table only delele_at value updated with current date and time.
Firstly we have to add a given code in our required model file.
use SoftDeletes;
protected $dates = [‘deleted_at’];
After this, we can use both cases.
$softDelete = Post::where(‘id’, ‘=’, 1)->delete();
OR
$softDelete = Post::where(‘id’, ‘=’, 1)->softDeletes();
33. How to use aggregate functions in Laravel?
Ans. Laravel provides a variety of aggregate functions such as max, min, count,avg, and sum. We can call any of these functions after constructing our query.$users = DB::table(‘admin’)->count();
$maxComment = DB::table(‘blogs’)->max(‘comments’);
34. Which template engine laravel use?
Ans. Laravel uses “Blade Template Engine”. It is a straightforward and powerful templating engine that is provided with Laravel.
35.What is Eloquent ORM in Laravel?
Ans. The Eloquent ORM present in Laravel offers a simple yet beautiful ActiveRecord implementation to work with the database. Here, each database table offers a corresponding model which is used to interact with the same table. We can create Eloquent models using the make:model command.
It has many types of relationships.
One To One relationships
One To Many relationships
Many To Many relationships
Has Many Through relationships
Polymorphic relationships
Many To Many Polymorphic relationships
36. How to use soft delete in laravel?
Ans. Soft delete is a laravel feature that helps When models are soft deleted, they are not actually removed from our database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, we have to specify the soft delete property on the model like this.In model we have to use namespace
use Illuminate\Database\Eloquent\SoftDeletes;and we can use this
use SoftDeletes; in our model property.After that when we will use delete() query then records will not remove from our database. then a deleted_at timestamp is set on the record.
1. What is Laravel?
Ans. Laravel is a free open source “PHP framework” based on the 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.
2.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.
3.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 Urls 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’);
4. 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.
5. 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’);
});
6. 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();
7. How to enable query log in Laravel ?
Ans. Use the enableQueryLog method to enable query log in LaravelDB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();
8. List some default packages provided by Laravel 5.6 ?
Ans.A.Below are a list of some official/ default packages provided by Laravel
Cashier
Envoy
Passport
Scout
Socialite
Horizon
9.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.
10. 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 usesclass User extends Eloquent{
protected $table=”my_user_table”;}
11.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.
12.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
13.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.
14.How to check request is ajax or not ?
Ans. In Laravel, we can use $request->ajax() method to check request is ajax or not.Example:public function saveData(Request $request)
{
if($request->ajax()){
return “Request is of Ajax Type”;
}
return “Request is of Http type”;
}
15. 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
16. How to extend login expire time in Auth?
Ans.You can extend the login expire time with config\session.php this file location. Just update lifetime the variables value. By default it is ‘lifetime’ => 120. According to your requirement update this variable.
17.What is middleware in Laravel?
Ans.In Laravel, middleware operates as a bridge and filtering mechanism between a request and response. It verifies the authentication of the application users and redirects them according to the authentication results. We can create a middleware in Laravel by executing the following command.Example: If a user is not authenticated and it is trying to access the dashboard then, the middleware will redirect that user to the login page.Get ready to be answerable to this question. This is a favorite Laravel Interview Questions of many interviewers. Don’t let this question waste the opportunity. Read it twice.
18.What is Database Migration and how to use this in Laravel?
Ans. It is a type of version control for our database. It is allowing us to modify and share the application’s database schema easily.A migration file contains two methods up() and down().up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.
19. How to pass CSRF token with ajax request?
Ans.In between head, tag put <meta name=”csrf-token” content=”{{ csrf_token() }}”> and in Ajax, we have to add
$.ajaxSetup({
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
}
});up() is used to add new tables, columns, or indexes database and the down() is used to reverse the operations performed by the up method.
20.How to get data between two dates in Laravel?
Ans.In Laravel, we can use whereBetween() function to get data between two dates.
Example
Blog::whereBetween(‘created_at’, [$dateOne, $dateTwo])->get();
21.How to turn off CSRF protection for a particular route in Laravel?
Ans.We can add that particular URL or Route in $except variable. It is present in the app\Http\Middleware\VerifyCsrfToken.php file.
Example
class VerifyCsrfToken extends BaseVerifier {
protected $except = [
‘Pass here your URL’,
];
}
22. What is the use of dd() in Laravel?
Ans. It is a helper function which is used to dump a variable’s contents to the browser and stop the further script execution. It stands for Dump and Die.
Example
dd($array);
23. What is PHP artisan in laravel? Name some common artisan commands?
Ans.Artisan is a type of the “command line interface” using in Laravel. It provides lots of helpful commands for you while developing your application. We can run these command according to our need.
Laravel supports various artisan commands like
php artisan list;
php artisan –version
php artisan down;
php artisan help;
php artisan up;
php artisan make:controller;
php artisan make:mail;
php artisan make:model;
php artisan make:migration;
php artisan make:middleware;
php artisan make:auth;
php artisan make:provider etc.;
24.What is the difference between {{ $username }} and {!! $username !!} in Laravel?
Ans. {{ $username }} is simply used to display text contents but {!! $username !!} is used to display content with HTML tags if exists.
25. How to use session in laravel?
Ans. 1. Retrieving Data from session
session()->get(‘key’);2. Retrieving All session data
session()->all();3. Remove data from session
session()->forget(‘key’); or session()->flush();4. Storing Data in session
session()->put(‘key’, ‘value’);
26.How to use mail() in laravel?
Ans.Laravel provides a powerful and clean API over the SwiftMailer library with drivers for Mailgun, SMTP, Amazon SES, SparkPost, and send an email. With this API, we can send email on a local server as well as the live server.
Here is an example through the mail()
Laravel allows us to store email messages in our views files. For example, to manage our emails, we can create an email directory within our resources/views directory.
Example
public function sendEmail(Request $request, $id)
{
$user = Admin::find($id);
Mail::send(’emails.reminder’, [‘user’ => $user], function ($m) use ($user) {
$m->from(‘info@bestinterviewquestion.com’, ‘Reminder’);
$m->to($user->email, $user->name)->subject(‘Your Reminder!’);
});
}
27. How to use cookies in laravel?
Ans.1. How to set Cookie
To set cookie value, we have to use Cookie::put(‘key’, ‘value’);
2. How to get Cookie
To get cookie Value we have to use Cookie::get(‘key’);
3. How to delete or remove Cookie
To remove cookie Value we have to use Cookie::forget(‘key’)
4. How to check Cookie
To Check cookie is exists or not, we have to use Cache::has(‘key’)
28. What is Auth? How is it used?
Ans.Laravel Auth is the process of identifying the user credentials with the database. Laravel managed it’s with the help of sessions which take input parameters like username and password, for user identification. If the settings match then the user is said to be authenticated.Auth is in-built functionality provided by Laravel; we have to configure.We can add this functionality with php artisan make: authAuth is used to identifying the user credentials with the database.
low web application
29. How to make a constant and use globally?
Ans. You can create a constants.php page in config folder if does not exist. Now you can put constant variable with value here and can use with Config::get(‘constants.VaribleName’);
Example
return [
‘ADMINEMAIL’ => ‘info@bestinterviewquestion.com’,
];
Now we can display with
Config::get(‘constants.ADMINEMAIL’);
30. What is with() in Laravel?
Ans. with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
31.How to get user’s ip address in laravel?
Ans. You can use request()->ip()You can also use : Request::ip() but in this case we have to call namespace like this : Use Illuminate\Http\Request;
32.What are the difference between softDelete() & delete() in Laravel?
Ans. 1. delete()
In case when we used to delete in Laravel then it removed records from the database table.
Example:
$delete = Post::where(‘id’, ‘=’, 1)->delete();
2. softDeletes()
To delete records permanently is not a good thing that’s why laravel used features are called SoftDelete. In this case, records did not remove from the table only delele_at value updated with current date and time.
Firstly we have to add a given code in our required model file.
use SoftDeletes;
protected $dates = [‘deleted_at’];
After this, we can use both cases.
$softDelete = Post::where(‘id’, ‘=’, 1)->delete();
OR
$softDelete = Post::where(‘id’, ‘=’, 1)->softDeletes();
33. How to use aggregate functions in Laravel?
Ans. Laravel provides a variety of aggregate functions such as max, min, count,avg, and sum. We can call any of these functions after constructing our query.$users = DB::table(‘admin’)->count();
$maxComment = DB::table(‘blogs’)->max(‘comments’);
34. Which template engine laravel use?
Ans. Laravel uses “Blade Template Engine”. It is a straightforward and powerful templating engine that is provided with Laravel.
35.What is Eloquent ORM in Laravel?
Ans. The Eloquent ORM present in Laravel offers a simple yet beautiful ActiveRecord implementation to work with the database. Here, each database table offers a corresponding model which is used to interact with the same table. We can create Eloquent models using the make:model command.
It has many types of relationships.
One To One relationships
One To Many relationships
Many To Many relationships
Has Many Through relationships
Polymorphic relationships
Many To Many Polymorphic relationships
36. How to use soft delete in laravel?
Ans. Soft delete is a laravel feature that helps When models are soft deleted, they are not actually removed from our database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, we have to specify the soft delete property on the model like this.In model we have to use namespace
use Illuminate\Database\Eloquent\SoftDeletes;and we can use this
use SoftDeletes; in our model property.After that when we will use delete() query then records will not remove from our database. then a deleted_at timestamp is set on the record.