Laravel Interview Questions answer 2021

Laravel Interview Questions answer

What is Laravel Framework?

Laravel is an open-source PHP web application framework. It is a very well documented, expressive, and easy to learn framework. Laravel is very developer-friendly as the framework can help beginners as well as advanced users. As you grow as a developer you can go more deep into Laravel functionalities and give more robust and enterprise solutions.

Additionally, the framework is very scalable as you can use packages like Vapor to handle hundreds of thousands of requests using AWS serverless technology.


What is Laravel?

Laravel is a Symfony-based free open-source PHP web framework. It is created by Taylor Otwell and allows developers to write expressive, elegant syntax. Laravel comes with built-in support for user authentication and authorization which is missing in some most popular PHP frameworks like CodeIgniter, CakePHP. It one of the most popular PHP framework which is based on MVC architecture. It was written in PHP & initially released in June 2011. the latest version of laravel is Laravel 8, released on 8 Sep 2020. You will find here the best and latest Laravel Interview Questions and Answers that help you crack Laravel Interviews. You can also download the Laravel Interview Questions PDF from the given link between the post.

This article will walk you through basic Laravel interview questions to advanced questions.

Laravel Interview Questions  answer For Freshers

  1. What is the latest Laravel version?

The latest Laravel version is 8.x.

  1. Define Composer.

Composer is the package manager for the framework. It helps in adding new packages from the huge community into your laravel application.

For example, one of the most used packages for authentication will be Passport, for including that into your project, you can run the below command on your terminal:

composer requires laravel/passport

It generates a file(composer.json) in your project directory to keep track of all your packages. A default composer.json file of your laravel project will look something like below:


“name”: “laravel/laravel”,

“type”: “project”,

“description”: “The Laravel Framework.”,

“keywords”: [




“license”: “MIT”,

“require”: {

“php”: “^7.3|^8.0”,

“fideloper/proxy”: “^4.4”,

“fruitcake/laravel-cors”: “^2.0”,

“guzzlehttp/guzzle”: “^7.0.1”,

“laravel/framework”: “^8.12”,

“laravel/tinker”: “^2.5”



“require-dev”: {

“facade/ignition”: “^2.5”,

“fakerphp/faker”: “^1.9.1”,

“laravel/sail”: “^1.0.1”,

“mockery/mockery”: “^1.4.2”,

“nunomaduro/collision”: “^5.0”,

“phpunit/phpunit”: “^9.3.3”

} }


The “require” and “require-dev” keys in composer.json specify production and dev packages and their version constraints respectively.

Related: for Laravel Interview Questions answer

  1. What is the templating engine used in Laravel?

The templating engine used in Laravel is Blade. The blade gives the ability to use its mustache-like syntax with the plain PHP and gets compiled into plain PHP and cached until any other change happens in the blade file. The blade file has .blade.php extension.


  1. What are available databases supported by Laravel?

The supported databases in laravel are:



SQL Server




  1. What is an artisan?

Artisan is the command-line tool for Laravel to help the developer build the application. You can enter the below command to get all the available commands:


PHP artisan list: Artisan command can help in creating the files using the make command. Some of the useful make commands are listed below:


php artisan make:controller – Make Controller file

php artisan make:model – Make a Model file

php artisan make:migration – Make Migration file

php artisan make:seeder – Make Seeder file

php artisan make:factory – Make Factory file

php artisan make:policy – Make Policy file

php artisan make:command – Make a new artisan command


  1. How to define environment variables in Laravel?

The environment variables can be defined in the .env file in the project directory. A brand new laravel application comes with a .env.example and while installing we copy this file and rename it to .env and all the environment variables will be defined here.

Some of the examples of environment variables are APP_ENV, DB_HOST, DB_PORT, etc.


  1. Can we use Laravel for Full Stack Development (Frontend + Backend)?

Laravel is the best choice to make progressive, scalable full-stack web applications. Full-stack web applications can have a backend in laravel and the frontend can be made using blade files or SPAs using Vue.js as it is provided by default. But it can also be used to just provide rest APIs to a SPA application.

Hence, Laravel can be used to make full-stack applications or just the backend APIs only.


  1. How to put Laravel applications in maintenance mode?

Maintenance mode is used to put a maintenance page to customers and under the hood, we can do software updates, bug fixes, etc. Laravel applications can be put into maintenance mode using the below command:

php artisan down

And can put the application again on live using the below command:

php artisan up

Also, it is possible to access the website in maintenance mode by whitelisting particular IPs.


  1. What are the default route files in Laravel?

Below are the four default route files in the routes folder in Laravel:

web.php – For registering web routes.

api.php – For registering API routes.

console.php – For registering closure-based console commands.

channel.php – For registering all your event broadcasting channels that your application supports.


  1. What are migrations in Laravel?

In simple, Migrations are used to create database schemas in Laravel. In migration files, we store which table to create, update or delete.

Each migration file is stored with its timestamp of creation to keep track of the order in which it was created. As migrations go up with your code in GitHub, GitLab, etc, whenever anyone clones your project they can run `PHP artisan migrate` to run those migrations to create the database in their environment. A normal migration file looks like below:


use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

class CreateUsersTable extends Migration{


     * Run the migrations.


     * @return void


    public function up()    {

        Schema::create(‘users’, function (Blueprint $table) {



      // Create other columns




     * Reverse the migrations.


     * @return void


    public function down()    {


    } }


The up() method runs when we run `php artisan migrate` and down() method runs when we run `php artisan migrate:rollback`.

If we rollback, it only rolls back the previously run migration.

If we want to rollback all migrations, we can run ‘php artisan migrate:reset`.

If we want to rollback and run migrations, we can run `PHP artisan migrate:refresh`, and we can use `PHP artisan migrate:fresh` to drop the tables first and then run migrations from the start.


  1. What are seeders in Laravel?

Seeders in Laravel are used to put data in the database tables automatically. After running migrations to create the tables, we can run `php artisan db:seed` to run the seeder to populate the database tables.

We can create a new Seeder using the below artisan command:

php artisan make:seeder [className]

It will create a new Seeder like below:


use AppModelsAuthUser;

use IlluminateDatabaseEloquentModel;

use IlluminateDatabaseSeeder;



class UserTableSeeder extends Seeder {


     * Run the database seeds.


    public function run()    {

        factory(User::class, 10)->create();

    } }


The run() method in the above code snippet will create 10 new users using the User factory.

Factories will be explained in the next question.


  1. What are factories in Laravel?

Factories are a way to put values in fields of a particular model automatically. Like, for testing when we add multiple fake records in the database, we can use factories to generate a class for each model and put data in fields accordingly. Every new laravel application comes with database/factories/UserFactory.php which looks like below:


namespace DatabaseFactories;

use AppModelsUser;

use IlluminateDatabaseEloquentFactoriesFactory;

use IlluminateSupportStr;

class UserFactory extends Factory {


* The name of the factory’s corresponding model.


* @var string


protected $model = User::class;


* Define the model’s default state.


* @return array



public function definition()   {

return [

‘name’ => $this->faker->name,

’email’ => $this->faker->unique()->safeEmail,

’email_verified_at’ => now(),

‘password’ => ‘password hare’, // password

‘remember_token’ => Str::random(10),


} }


We can create a new factory using php artisan make:factory UserFactory –class=User.

The above command will create a new factory class for the User model. It is just a class that extends the base Factory class and makes use of the Faker class to generate fake data for each column. With the combination of factory and seeders, we can easily add fake data into the database for testing purposes.


  1. How to implement soft delete in Laravel?

Soft Delete means when any data row is deleted by any means in the database, we are not deleting the data but adding a timestamp of deletion.

We can add soft delete features by adding a trait in the model file like below.


use IlluminateDatabaseEloquentModel;

use IlluminateDatabaseEloquentSoftDeletes;


class Post extends Model {

use SoftDeletes;

protected $table = ‘posts’;

// …



Related: for Laravel Interview Questions answer

  1. What are Models?

With Laravel, each database table can have a model representation using a model file which can be used to interact with that table using Laravel Eloquent ORM.

We can create a model using this artisan command:

php artisan make:model Post

This will create a file in the models’ directory and will look like below:

class Post extends Model



* The attributes that are mass assignable.


* @var array


protected $fillable = [];


* The attributes that should be hidden for arrays.


* @var array


protected $hidden = [];


A Model can have properties like table, fillable, hidden, etc which defines properties of the table and model.

Advanced Laravel Interview Questions


  1. What are Relationships in Laravel?

Relationships in Laravel are a way to define relations between different models in the applications. It is the same as relations in relational databases.

Different relationships available in Laravel are:

  • One to One
  • One to Many
  • Many to Many
  • Has One Through
  • Has Many Through
  • One to One (Polymorphic)
  • One to Many (Polymorphic)
  • Many to Many (Polymorphic)


Relationships are defined as a method on the model class. An example of One to One relation is shown below.


namespace AppModels;

use IlluminateDatabaseEloquentModel;

class User extends Model{


     * Get the phone associated with the user.


    public function phone()    {

        return $this->hasOne(Phone::class);


The above method phone on the User model can be called like : `$user->phone` or `$user->phone()->where(…)->get()`.


We can also define One to Many relationships like below:


namespace AppModels;

use IlluminateDatabaseEloquentModel;

class User extends Model{


     * Get the addresses for the User.


    public function addresses()    {

        return $this->hasMany(Address::class);



Since a user can have multiple addresses, we can define a One to Many relations between the User and Address model. Now if we call `$user->addresses`, eloquent will make the join between tables and it will return the result.


  1. What is Eloquent in Laravel?

Eloquent is the ORM used to interact with the database using Model classes. It gives handy methods on class objects to make a query on the database.

It can directly be used to retrieve data from any table and run any raw query. But in conjunction with Models, we can make use of its various methods and also make use of relationships and attributes defined on the model.

Some examples of using the Eloquent are below:




`User::where(‘name’, ‘=’, ‘Eloquent’)->get()`


  1. What is throttling and how to implement it in Laravel?

Throttling is a process to rate-limit requests from a particular IP. This can be used to prevent DDOS attacks as well. For throttling, Laravel provides a middleware that can be applied to routes and it can be added to the global middlewares list as well to execute that middleware for each request.

Here’s how you can add it to a particular route:


Route::middleware(‘auth:api’, ‘throttle:60,1’)->group(function () {

Route::get(‘/user’, function () {





This will enable the /user route to be accessed by a particular user from a particular IP only 60 times in a minute.


  1. What are facades?

Facades are a way to register your class and its methods in Laravel Container so they are available in your whole application after getting resolved by Reflection.

The main benefit of using facades is we don’t have to remember long class names and also don’t need to require those classes in any other class for using them. It also gives more testability to the application.

The below image could help you understand why Facades are used for:

Facades in Laravel


  1. What are Events in Laravel?

In Laravel, Events are a way to subscribe to different events that occur in the application. We can make events to represent a particular event like user logged in, user logged out, user-created post, etc. After which we can listen to these events by making Listener classes and do some tasks like, user logged in then make an entry to audit logger of application.

For creating a new Event in laravel, we can call below artisan command:

php artisan make:event UserLoggedIn

This will create a new event class like below:


namespace AppEvents;

use AppModelsUser;

use IlluminateBroadcastingInteractsWithSockets;

use IlluminateFoundationEventsDispatchable;

use IlluminateQueueSerializesModels;

class UserLoggedIn{

    use Dispatchable, InteractsWithSockets, SerializesModels;


     * The user instance.


     * @var AppModelsUser


    public $user;


     * Create a new event instance.


     * @param  AppModelsUser  $user

     * @return void


    public function __construct(User $user)    {

        $this->user = $user;




Related: for Laravel Interview Questions answer

For this event to work, we need to create a listener as well. We can create a listener like this:

php artisan make:listener SetLogInFile –event=UserLoggedIn

The below resultant listener class will be responsible to handle when the UserLoggedIn event is triggered.

use AppEventsUserLoggedIn;

class SetLogInFile{


     * Handle the given event.


     * @param  AppEventsUserLoggedIn

     * @return void


    public function handle(UserLoggedIn $event)    {




  1. Explain logging in Laravel?

Laravel Logging is a way to log information that is happening inside an application. Laravel provides different channels for logging like file and slack. Log messages can be written on to multiple channels at once as well.

We can configure the channel to be used for logging in to our environment file or in the config file at config/logging.php.


  1. What is Localization in Laravel?

Localization is a way to serve content concerning the client’s language preference. We can create different localization files and use a laravel helper method like this: `__(‘auth.error’)` to retrieve translation in the current locale. These localization files are located in the resources/lang/[language] folder.


  1. What are Requests in Laravel?

Requests in Laravel are a way to interact with incoming HTTP requests along with sessions, cookies, and even files if submitted with the request.

The class responsible for doing this is IlluminateHttpRequest.

When any request is submitted to a laravel route, it goes through to the controller method, and with the help of dependency Injection, the request object is available within the method. We can do all kinds of things with the request like validating or authorizing the request, etc.


  1. How to do request validation in Laravel?

Request validation in laravel can be done with the controller method or we can create a request validation class that holds the rules of validation and the error messages associated with it.

One example of it can be seen below:


 * Store a new blog post.


 * @param  IlluminateHttpRequest  $request

 * @return IlluminateHttpResponse


public function store(Request $request){

    $validated = $request->validate([

        ‘title’ => ‘required|unique:posts|max:255’,

        ‘body’ => ‘required’,


// The blog post is valid…



  1. What is a Service Container in Laravel?

Service Container or IoC in laravel is responsible for managing class dependencies meaning not every file needs to be injected in class manually but is done by the Service Container automatically. Service Container is mainly used in injecting class in controllers like Request object is injected. We can also inject a Model based on id in route binding.

For example, a route like below:

Route::get(‘/profile/{id}’, ‘UserController@profile’);

With the controller like below.

public function profile(Request $request, User $id){



In the UserController profile method, the reason we can get the User model as a parameter is because of Service Container as the IoC resolves all the dependencies in all the controllers while booting the server. This process is also called route-model binding.

Laravel Interview Questions answer

  1. What is a Service Provider?

A Service Provider is a way to bootstrap or register services, events, etc before booting the application. Laravel’s own bootstrapping happens using Service Providers as well. Additionally, registers service container bindings, event listeners, middlewares, and even routes using its service providers.

If we are creating our application, we can register our facades in provider classes.


  1. What is the register and boot method in the Service Provider class?

The register method in the Service Provider class is used to bind classes or services to the Service Container. It should not be used to access any other functionality or classes from the application as the service you are accessing may not have loaded yet into the container.

The boot method runs after all the dependencies have been included in the container and now we can access any functionality in the boot method. Like you can create routes, create a view composer, etc in the boot method.


  1. How to define routes in Laravel?

Laravel Routes are defined in the routes file in routes/web.php for web application routes. Routes can be defined using IlluminateSupportFacadesRoute and calling its static methods such as to get, post, put, delete, etc.

use IlluminateSupportFacadesRoute;

Route::get(‘/home’, function () {

    return ‘Welcome to Home Sweet Home’;


A typical closure route looks like the above, where we provide the URI and the closure function to execute when that route is accessed.

Route::get(‘/hello’, ‘HomeController@index’);

Another way is like above, we can directly give the controller name and the method to call, this can again be resolved using Service Container.


  1. What are named routes?

A named route is a route definition with the name assigned to it. We can then use that name to call the route anywhere else in the application.

Route::get(‘/hello’, ‘HomeController@index’)->name(‘index’);

This can be accessed in a controller using the following:

return redirect()->route(‘index’);


Related: for Laravel Interview Questions answer


  1. What are route groups?

Route Groups in laravel is used when we need to group route attributes like middlewares, prefixes, etc. we use route groups. It saves us a headache to put each attribute to each route.


Route::middleware([‘throttleMiddleware’])->group(function () {

Route::get(‘/’, function () {

// Uses throttleMiddleware


Route::get(‘/user/profile’, function () {

// Uses throttleMiddleware




  1. What is Middleware and how to create one in Laravel?

Middleware gives developers the ability to inspect and filter incoming HTTP requests of our application. One such middleware that ships with laravel are the authentication middleware which checks if the user is authenticated and if the user is authenticated it will go further in the application otherwise it will throw the user back to the login screen.

We can always create a new middleware for our purposes. For creating a new middleware we can use the below artisan command:

php artisan make:middleware CheckFileIsNotTooLarge

The above command will create a new middleware file in the app/Http/Middleware folder.


  1. How to create a route for resources in laravel?

For creating a resource route we can use the below command:

Route::resource(‘blogs’, BlogController::class);

This will create routes for six actions index, create, store, show, edit, update and delete.


  1. What is dependency Injection in Laravel?

The Laravel Service Container or IoC resolves all of the dependencies in all controllers. So we can type-hint any dependency in controller methods or constructors. The dependency in methods will be resolved and injected in the method, this injection of resolved classes is called dependency Injection.

Laravel Interview Questions answer

  1. What are collections?

Collections in laravel are a wrapper over an array of data in Laravel. All of the responses from Eloquent ORM when we query data from the database are collections (Array of data records).

Collections give us handy methods over them to easily work with the data like looping over data or doing some operation on it.


  1. What are contracts?

Laravel Contracts are a set of interfaces with implementation methods to complete the core tasks of Laravel.

Laravel Contracts

Few examples of contracts in Laravel are Queue and Mailer. Queue contract has an implementation of Queuing jobs while Mailer contract has an implementation to send emails.

What are the Laravel guards?

The guard in Laravel is used to define the user authentication for each request. The Guards also provide a definition of user information storage and retrieval by the system. The session guard is a default guard in Laravel that is used to maintain the state using session storage and cookies. A web guard is used to store and retrieve session information. API guard is used for authenticating users and requests. These are some examples of default Laravel guard, and you can also create your own guard in Laravel.

Laravel Interview Questions answer

Related: for Laravel Interview Questions answer

Scroll to Top