Home >> Interviews Q & A >> Top 50 Laravel Interview Questions

Top 50 Laravel Interview Questions

Laravel Interview Questions: Latest Top 50 Best Laravel Interview Questions Answers for Freshers and Experienced Laravel Developer. Laravel is a free, open-source PHP web framework, created by Taylor Otwell.
Laravel Interview Questions
Q:-1 What is Laravel?
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.
Q:-1(a) What is Server Requirements for Laravel 5.6?
  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
Q:-2 How to Install Laravel via Composer?
composer create-project --prefer-dist laravel/laravel myproject

For Other Info Please check official website of Laravel

Q:-2(a) How to Install any Specific version of Laravel via Composer?
//Composer Command To Install Laravel:
composer create-project --prefer-dist laravel/laravel ProjectName "VersionNo.*"

//Example: Install Laravel 5.4 using Composer
composer create-project --prefer-dist laravel/laravel blog "5.4.*"

For Other Info Please check official website of Laravel

You may also like - PHP OOPS Interview Questions
Q:-3 What is Lumen?
  1. Lumen is a micro-framework provided by Laravel.
  2. It is developed by creator of Laravel Taylor Otwell.
  3. It is mostly used for creating RESTful API’s & microservices.
  4. Lumen is built on top components of Laravel.
Q:-3(a) How to Install Lumen via Composer?

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

composer create-project --prefer-dist laravel/lumen myproject
Q:-4 What is php artisan?
  1. Artisan is the command-line interface included with Laravel.
  2. It provides a number of helpful commands that can assist you while you build your application.
  3. To view a list of all available Artisan commands, you may use the list command:
  4. php artisan list //it will all commands
    php artisan --version	//to check current installed laravel version
    
Q:-4(a) List mostly used artisan commands?
  1. To view a list of all available Artisan commands, you may use the list command:
  2. php artisan list //it will all commands
    php artisan --version	//to check current installed laravel version
    
  3. Mostly used Artisan commands are:
  4. php artisan list //it will all commands
    php artisan --version	//to check current installed laravel version
    
    //Clear view caches
    php artisan view:clear
    
    //Clear cache
    php artisan cache:clear
    
    //Make authorization views and scaffolding
    php artisan make:auth
    
    //Make a new model
    php artisan make:model model-name
    
    //Make a new empty controller
    php artisan make:controller MyController
    
    

    Read more in details

Q:-5 List benefits of using Laravel over other PHP frameworks?

Reasons why Laravel is the best PHP framework:

  1. Artisan - A Command-Line Interface
  2. Migrations & Seeding
  3. Blade Template Engine
  4. Middleware - HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
  5. Eloquent ORM + Built-in Database Query Builder
  6. Routing (RESTful routing)
  7. Inbuilt packages - Authentication, Cashier, Scheduler, SSH, Socialite
  8. Security
  9. Unit Testing - Built-in unit testing and simply readable impressive syntax
  10. Caching - Laravel provides an expressive, unified API for various caching backends

Read more in detail about these

Q:-6 List most important packages provided by Laravel?

Following are some official packages provided by Laravel:

Authentication:

Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box.

//Make authorization views and scaffolding
php artisan make:auth
Passport:
  1. In Short, Laravel provides Passport for API Authentication.
  2. Laravel Passport is an OAuth2 server and API authentication package that is simple to use
Cashier:

Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services

Scout:
  1. Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models.
  2. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records
  3. Currently, Scout ships with an Algolia driver; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations.
Socialite:
  1. Laravel's Socialite package makes it simple to authenticate your users to social login
  2. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket.
You may also like - Core PHP Interview Questions
Q:-7 How to turn off CRSF in Laravel?
Disable CSRF protection for all routes In Laravel:
Remove or comment out this line in app\Http\Kernel.php

\App\Http\Middleware\VerifyCsrfToken::class,
To turn off or disable CRSF protection for some specific routes in Laravel:
open "app/Http/Middleware/VerifyCsrfToken.php" file and add your routes in $except array.
namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
		'stripe/*',
		'payment/verify/{id}/*',
		'some/route/path',
    ];
}
Q:-8 How can you change your default database type?

By default Laravel is configured to use MySQL.

In order to change your default database edit your config/database.php

search for 'default' => env('DB_CONNECTION', 'mysql')
and change it to whatever you want (like 'default' => env('DB_CONNECTION', 'sqlite'))
Q:-9 What is ORM?

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

You may also like - Node.js Interview Questions and Answers
Q:-9(a) Which ORM are being used by laravel?

Eloquent ORM is being used by Laravel.

  • 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.
  • All Eloquent models extend Illuminate\Database\Eloquent\Model class
Eloquent Model Examples:

The easiest way to create a model instance is using the make:model artisan command

php artisan make:model User
If you would like to generate a database migration when you generate the model, use:
php artisan make:model User --migration

//OR 

php artisan make:model User -m

Now look following Example:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
	//Your code 
}

Eloquent will assume the User model stores records in the users table

You may specify a custom table by defining a table property in your model, like below:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_tables';
}
Q:-9(b) List types of relationships available in Laravel Eloquent?
  1. Eloquent relationships are defined as methods on your Eloquent model classes
  2. Relationships supported by Laravel Eloquent ORM:
    1. One To One - hasOne
    2. One To Many - hasMany
    3. One To Many(Inverse) - belongsTo
    4. Many To Many - belongsToMany
    5. Has Many Through - hasManyThrough
    6. Polymorphic Relations
    7. Many To Many Polymorphic Relations

Visit official website of Laravel for more details

Q:-10 Which Template Engine used by Laravel?

Blade is the simple, yet powerful templating engine provided with Laravel.

Q:-10(a) What is benefits of using "Blade" Template in 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.

Visit official website of Laravel for more details

Q:-11 How to enable maintenance mode in Laravel?

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

// Enable maintenance mode
php artisan down

// Disable maintenance mode
php artisan up
Q:-12 What is the purpose of using dd() function in laravel?

dd() – Stands for "Dump and Die"

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

Q:-13 What is Middleware in Laravel?

Middleware provide a convenient mechanism for filtering all HTTP requests entering in your application. ...read more about Laravel Middleware.

Q:-14 Explain Laravel Service Container?
The Laravel Service Container is a powerful tool for managing class dependencies and performing dependency injection.

Dependency injection is technique which means: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

Almost all of your service container bindings will be registered within service providers

Dependency Injection Benefits:
  1. More Reusable Code
  2. More Testable Code
  3. More Readable Code
Q:-15 What are Service Providers in Laravel?
  1. 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.
  2. Bootstrapping mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.
Q:-15(a) How do you register a Service Provider?
  1. All service providers extend the Illuminate\Support\ServiceProvider class.
  2. Most service providers contain a register and a boot method.
  3. Within the register method, you should only bind things into the service container.
php artisan make:provider MyServiceProvider
Q:-16 What are Laravel Facades?

In Short, Facades provide a "static" interface to classes that are available in the application's service container.

All of Laravel's facades are defined in the Illuminate\Support\Facades namespace.

Facades have many benefits. They provide a short and memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually.

Facades Vs Helper Functions: There is absolutely no practical difference between facades and helper functions. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:

return View::make('welcome');  // facade call

return view('welcome');	// helper call
You may also like - RESTful APIs Interview Questions
Q:-17 Explain Events in Laravel?
  1. Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application
  2. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.
  3. Don't worry if you don't see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.
  4. A single event can have multiple listeners that do not depend on each other.
Q:-18 What is Fillable Attribute in a Laravel Model?

In eloquent ORM, $fillable is an array which contains all those fields of table which can be filled using mass-assignment.

Mass assignment, means to send an array to the model to directly create a new record in Database

class User extends Model {
    protected $fillable = ['name', 'email', 'mobile']; // All fields inside $fillable array can be mass-assign
}
Q:-19 What is Guarded Attribute in a Laravel Model?
Guarded is the reverse of fillable.

If fillable specifies which fields to be mass assigned, guarded specifies which fields are not mass assignable.

class User extends Model {
    protected $guarded = ['role']; // All fields inside the $guarded array is not mass-assignable
}

If you want to block all fields from being mass-assign you can just do this.

protected $guarded = ['*'];

$fillable serves as a "white list", $guarded functions like a black list. you should use either $fillable or $guarded.

Q:-20 What are Closures in Laravel?

A Closure is an anonymous function. Closures are often used as a callback methods and can be used as a parameter in a function.

Q:-21 What are Laravel Contracts?
  1. Laravel's Contracts are a set of interfaces that define the core services provided by the framework.
  2. For example, a Illuminate\Contracts\Queue\Queue contract defines the methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed for sending e-mail
  3. Each contract has a corresponding implementation provided by the framework.
Q:-22 What are Traits in Laravel?

As of PHP 5.4, we now have a mechanism for reusing code, called Traits.

Q:-23 How to get Logged in user info in Laravel?

The laravel Auth Facade is used to get the autheticated user data as

use Illuminate\Support\Facades\Auth;

$user = Auth::user();
print_r($user);
Q:-24 How to enable query log in Laravel?

Laravel can optionally log in memory all queries that have been run for the current request

//Enable query log
DB::connection()->enableQueryLog();

//See query log
$queries = DB::getQueryLog();

//Last executed query
$last_query = end($queries);
You may also like - MongoDB Interview Questions
Q:-25 Does Laravel support Caching?
  1. Yes, Laravel supports popular caching mechanism like Memcached and Redis.
  2. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system.
  3. For large projects it is recommended to use Memcached or Redis.
Q:-26 What is Laravel Elixir?
Q:-27 What is Laravel Mix?
Q:-28 How can you display HTML with Blade in Laravel?
{!! $text !!}
Q:-29 List out databases that laravel supports?

Currently, Laravel supports four databases:

  1. MySQL
  2. PostgreSQL
  3. SQLite
  4. SQL Server
Note:

you can use NoSQL databses with laravel by installing their packages.

Laravel doesn't support mongoDB out of the box, you'll have to install a third party package or create your own implementation. I'd suggest using https://github.com/jenssegers/laravel-mongodb , it seems a pretty popular package on packagist atleast. Or you could use the php mongodb class https://secure.php.net/manual/en/class.mongodb.php.

Q:-30 How to use custom table in Laravel Model ?

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

class Article extends Eloquent {
    protected $table="custom_table_name";
}  
Q:-31 How To Use Select Query In Laravel?
Using Eloquent ORM:
$result = App\User::all(); // Find all records
$result = App\User::find(1); // Find by AutoIncrement ID
Using Query Builder:
$result = DB::table('users')->where('id', 1)->get(); // Find by ID
Q:-32 How To Use Insert Query In Laravel?
Using Eloquent ORM:
class UserController extends Controller
{
    /**
     * Create a new user instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $user = new User;
        $user->name = $request->name;
        $user->role = $request->role;
        $user->save();
    }
Using Query Builder:
$result = DB::table('users')->insert(
    ['name' => 'Full Stack Tutorials', 'role' => 'author']
);

//If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
    ['name' => 'Full Stack Tutorials', 'role' => 'author']
);
Q:-33 How To Use Update Query In Laravel?
Using Eloquent ORM:
$result = User::where('id',1)->update(['name'=>'Full Stack Tutorials']);
Using Query Builder:
$result = DB::table('users')->where('id', 1)->update(['name' => 'Full Stack Tutorials']);
Q:-34 How To Use Delete Query In Laravel?
Using Eloquent ORM:
$result = User::where('id',$id)->delete();
Using Query Builder:
$result = DB::table('users')->where('id', $id)->delete();
You may also like - MySQL Interview Questions
Q:-35 Is Laravel application secure?

Laravel is a development framework and, as such, it won't make your server more secure, just your application. Laravel features allow you to use everything securely. All the data is sanitized where needed unless you're using Laravel with raw queries.

Q:-36 What are Accessors and Mutators in Eloquent and why should you use them?

Laravel accessors and mutators are custom, user defined methods that allow you to format Eloquent attributes.

  1. Accessors:
    Accessors are used to format attributes when you retrieve them from the database
  2. Mutators:
    Mutators are used to format attributes before saving them into the database
Q:-37 How do I perform dependency injection in Laravel?
Q:-38 What are Bundles, Reverse Routing & IoC container?
Q:-39 How do I log an error?

By default, Laravel is configured to create a log file for your application in the storage/logs directory.

Log files are in storage/logs/laravel.log, laravel.log is the default filename.

You may write information to the logs using the Log facade

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        Log::info('Showing user profile for user: '.$id);

        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

The logger provides the eight logging levels defined in RFC 5424: emergency, alert, critical, error, warning, notice, info and debug.

you can visit official website to read in more detail

Q:-39(a) What is Monolog library in Laravel?

Laravel utilizes the Monolog library, which provides support for a variety of powerful log handlers.

Q:-40 In which language Laravel is written ?

Laravel is written in PHP.

Q:-41 Exceptions are handled by which class in Laravel?

In Laravel exceptions are handled by App\Exceptions\Handler class.

This class contains two methods:

  1. report
  2. render
Q:-42 What is Serialization in Laravel?

In RESTful APIs, sometime you need to convert your models and relationships to arrays or JSON. this can be done using methods provided by Eloquent.

Convert into Array:

$posts = App\Post::all();
return $posts->toArray();

Convert into JSON:

$posts = App\Post::all();
return $posts->toJson();
Q:-43 What is Response in Laravel?

All Routes and Controllers should return a response to be sent back to the user's browser.

Laravel provides several different ways to return responses:

  • View Responses
  • JSON Responses
  • File Downloads
  • File Responses
  • Response Macros
  • Redirecting To Named Routes
  • Redirecting To Controller Actions
  • Redirecting To External Domains
  • Redirecting With Flashed Session Data
Q:-43(a) What is Response Macros in Laravel?

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Register the application's response macros.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('caps', function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}


return response()->caps('foo');
Q:-44 What is Rate Limiting OR Throttle in Laravel?

Rate Limit, means sometime you need to retrict access of routes within your application.

Rate Limit can be implemented in Laravel using Throttle Middleware.

The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes.

For example, let's specify that an authenticated user may access the following group of routes 60 times per minute:

Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

If required, you can make it dynamic using model's attribute (e.g. - in our case suppose it's - rate_limit).

Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});
You may also like - React.js Interview Questions
Q:-45 What is Lazy vs Eager Loading in Laravel?

Laravel Eloquent ORM provides two type of loading.

  1. Lazy Loading: By default, accessing data in eloquent is "Lazy loaded"
  2. Eager Loading: This can be achieved using with() in Eloquent. Eager loading alleviates the N + 1 query problem.
namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

class Author extends Model
{
    public function book() {
        return $this->hasMany('App\Book');
    }
}
#Example: Lazy Loading
$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}
#Example: Eager Loading
$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

//Eager Loading Multiple Relationships

$books = App\Book::with(['author', 'publisher'])->get();
Q:-46 How to get current environment in Laravel?

$environment = App::environment();

Q:-47 What's New in Laravel 5.8?

Laravel 5.8 is now released and has many improvements, addition and some breaking changes.

Major Upgrade or Breaking Changes:
  1. Caching TTL
  2. Deprecated Helper Functions
  3. Dotenv 3.0
  4. Carbon version 2
  5. Notifications Package
  6. Testing PHPUnit 8
  7. Password Length
Improvements:
  1. Error Page
  2. Artisan Call Improvements
  3. Email Validation
  4. Eloquent Resource Key Preservation
  5. Higher Order orWhere Eloquent Method
  6. JSON in MYSQL
  7. Correct Pluralisation
  8. Mock / Spy Testing Helper Methods
New Addition:
  1. Artisan Serve Improvements
  2. Auto-Discovery Of Model Policies
  3. HasOneThrough Relationship
  4. Token Guard Token Hashing
  5. Default Scheduler Timezone
  6. Multiple Broadcast Authentication Guards

Laravel 5.8 Latest Updates

Full Stack Tutorials

Author @FullStackTutorials | View all Articles