All interview topics
Full-Stack, Web & Mobile

Laravel Interview Questions and Answers

Practice Laravel interview questions and answers organized by difficulty, with revealable explanations and related topics.

41 questionsEntry → Expert

Entry questions

4 questions
  1. Question 1
    Entry

    What are some benefits of Laravel over other Php frameworks?

    • Laravel
    Reveal answer

    Setup and customisation 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

  2. Question 2
    Entry

    Is there any CLI for Laravel?

    • Laravel
    Reveal answer

    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 commands: 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

  3. Question 3
    Entry

    What is the Laravel?

    • Laravel
    Reveal answer

    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.

  4. Question 4
    Entry

    Why do you prefer using Laravel?

    • Laravel
    Reveal answer

    Simple MVC that can be extended easily Clean and secure routing Powerful Eloquent ORM for database Migrations Third party plugins

Mid questions

18 questions
  1. Question 1
    Mid

    What are named routes in Laravel?

    • Laravel
    Reveal answer

    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');
    
  2. Question 2
    Mid

    What is reverse routing in Laravel?

    • Laravel
    Reveal answer

    In Laravel reverse routing is generating URL’s based on route declarations.Reverse routing makes your application so much more flexible. For example the below route declaration tells Laravel to execute the action “login” in the users controller when the request’s URI is ‘login’. http://mysite.com/login

    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 create a link like http://mysite.com/login in view.

  3. Question 3
    Mid

    How to Rollback one specific migration in Laravel?

    • Laravel
    Reveal answer

    Rollback one step. Natively.

    php artisan migrate:rollback --step=1
    
  4. Question 4
    Mid

    How do you check “if not null” with Eloquent?

    • Laravel
    Reveal answer

    Eloquent has a method for that (Laravel 4./5.);

    Model::whereNotNull('sent_at')
    Laravel 3:
    Model::where_not_null('sent_at')
    
  5. Question 5
    Mid

    List some Aggregates methods provided by query builder in Laravel ?

    • Laravel
    Reveal answer

    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()
    $products = DB::table(‘products’)->count();
    max()
    $price = DB::table(‘orders’)->max(‘price’);
    min()
    
    $price = DB::table(‘orders’)->min(‘price’);
    avg()
    *$price = DB::table(‘orders’)->avg(‘price’);
    sum()
    $price = DB::table(‘orders’)->sum(‘price’);
    
  6. Question 6
    Mid

    What is Closure in Laravel?

    • Laravel
    Reveal answer

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

    function handle(Closure $closure) {
      $closure('Hello World!');
    }
    handle(function($value){
      echo $value;
    });
    
  7. Question 7
    Mid

    What are the benefits of using Vue.js with Laravel?

    • Laravel
    Reveal answer

    Vue is the default to spin up with a laravel project. It comes packaged with every fresh laravel project. As it has official support, you can be sure that it’ll be maintained for a long time with the project architectures in mind coupling Vue & Laravel. The whole Laravel community is biased to Vuejs which makes packages related to vue+laravel more available.

  8. Question 8
    Mid

    How do you generate event and listeners?

    • Laravel
    Reveal answer

    Laravel's events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. The EventServiceProvider included with your Laravel application provides a convenient place to register all of your application's event listeners. The listen property contains an array of all events (keys) and their listeners (values).

    To generate events and listeners add listeners and events to your EventServiceProvider and use the event:generate command. php artisan event:generate

  9. Question 9
    Mid

    How do you do soft deletes?

    • Laravel
    Reveal answer

    Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

    class User extends Model {
      public function scopePopular($query)
      {
        return $query->where('votes', '>', 100);
      }
    public function scopeWomen($query)
    {
      return $query->whereGender('W');
    }
    }
    Usage:
    $users = User::popular()->women()->orderBy('created_at')->get();
    

    Sometimes you may wish to define a scope that accepts parameters. Dynamic scopes accept query parameters:

    class User extends Model {
      public function scopeOfType($query, $type)
      {
        return $query->whereType($type);
      }
    }
    Usage:
    $users = User::ofType('member')->get();
    
  10. Question 10
    Mid

    What are query scopes?

    • Laravel
    Reveal answer

    Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application.

    public function scopePopular($query)
    {
      return $query->where('votes', '>', 100);
    }
    

    Consider:

    $users = App\User::popular()->active()->orderBy('created_at')->get();
    
  11. Question 11
    Mid

    What is the benefit of eager loading, when do you use it?

    • Laravel
    Reveal answer

    When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem when we have nested objects (like books -> author). We can use eager loading to reduce this operation to just 2 queries.

  12. Question 12
    Mid

    What is Laravel Passport?

    • Laravel
    Reveal answer

    Laravel Passport is native OAuth 2 server for Laravel apps. It uses the League OAuth2 Server package as a dependency but provides a simple, easy-to-learn and easy-to-implement syntax. Passport exposes a JSON API for your frontend to consume to let you manage your clients and tokens. Out of the box, Passport comes with Vue components that show how you might want to interact with this API in your app. You could use these components and call it done, or you could write your own tool to interact with the API.

  13. Question 13
    Mid

    How do you generate migrations?

    • Laravel
    Reveal answer

    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. To create a migration, use the make:migration Artisan command:

    php artisan make:migration create_users_table The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

  14. Question 16
    Mid

    How do you mock a static facade methods?

    • Laravel
    Reveal answer

    Facades provide a "static" interface to classes that are available in the application's service container. Unlike traditional static method calls, facades may be mocked. We can mock the call to the static facade method by using the shouldReceive method, which will return an instance of a Mockery mock.

    // actual code
    $value = Cache::get('key');// testing
    Cache::shouldReceive('get')
    ->once()
    ->with('key')
    ->andReturn('value');
    
  15. Question 17
    Mid

    What are Queues and Job workers?

    • Laravel
    Reveal answer

    Laravel queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer/postpone the processing of a time consuming task until a later time. Laravel includes a queue worker that will process new jobs as they are pushed onto the queue. You may run the worker using the queue:work Artisan command.

  16. Question 18
    Mid

    List types of relationships available in Laravel Eloquent?

    • Laravel
    Reveal answer

    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

  17. Question 19
    Mid

    What do you know about query builder in Laravel?

    • Laravel
    Reveal answer

    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.

    Some QB features: Chunking Aggregates Selects Raw Expressions Joins Unions Where Ordering, Grouping, Limit, & Offset

  18. Question 20
    Mid

    Where can you easily hook on validation in Laravel 5.x?

    • Laravel
    Reveal answer

    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.

Senior questions

5 questions
  1. Question 1
    Senior

    Where can you inject authentication checks on an API request?

    • Laravel
    Reveal answer

    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.

  2. Question 14
    Senior

    Where can you inject authentication checks on an API request?

    • Laravel
    Reveal answer

    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.

  3. Question 15
    Senior

    Explain the structure of the Migration Class

    • Laravel
    Reveal answer

    A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

  4. Question 16
    Senior

    Why do we need Traits in Laravel?

    • Laravel
    Reveal answer

    Traits have been added to PHP for a very simple reason: PHP does not support multiple inheritance. Simply put, a class cannot extends more than on class at a time. This becomes laborious when you need functionality declared in two different classes that are used by other classes as well, and the result is that you would have to repeat code in order to get the job done without tangling yourself up in a mist of cobwebs. Enter traits. These allow us to declare a type of class that contains methods that can be reused. Better still, their methods can be directly injected into any class you use, and you can use multiple traits in the same class. Let's look at a simple Hello World example. trait SayHello

    {
      private function hello()
      {
        return "Hello ";
      }
    private function world()
    {
      return "World";
    }
    }
    trait Talk
    {
      private function speak()
      {
        echo $this->hello() . $this->world();
      }
    }
    class HelloWorld
    {
      use SayHello;
      use Talk;
      public function __construct()
      {
        $this->speak();
      }
    }
    $message = new HelloWorld();
    // returns "Hello World";
    
  5. Question 18
    Senior

    What is Autoloader in PHP?

    • Laravel
    Reveal answer

    Autoloaders define ways to automatically include PHP classes in your code without having to use statements like require and include. PSR-4 would allow for simpler folder structures, but would prevent us from knowing the exact path of a class just by looking at the fully qualified name. PSR-0 on the other hand is chaotic on the hard drive, but supports developers who are stuck in the past (the underscore-in-class-name users) and helps us discern the location of a class just by looking at its name.

Expert questions

3 questions
  1. Question 1
    Expert

    How does Laravel use IoC?

    • Laravel
    Reveal answer

    The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run- time, allowing for greater flexibility as dependency implementations may be swapped easily. The IoC-Container is a component that knows how instances are created and knows of all their underlying dependencies and how to resolve them.

  2. Question 19
    Expert

    What are some Differences and Similarities Between Lumen and Laravel?

    • Laravel
    Reveal answer

    Lumen is not designed to replace Laravel, rather, it is a more specialized (and stripped-down) framework designed for micro-services and APIs. It took away unneeded features for an API such as HTTP sessions and cookies, and also limited the number of configuration options. Out-of-the-box, Lumen sacrified the flexibility of Laravel for speed. However, you can add Laravel components to Lumen to extend it, so it can be used for more than just micro- services and API. However, if your goal is to extend Lumen to become a website, you might as well use Laravel instead. They also have different use cases. Lumen and Laravel are meant to work together. For APIs and services are frequently get called, use Lumen. For user-facing applications, use Laravel.

  3. Question 20
    Expert

    What do you know about service providers?

    • Laravel
    Reveal answer

    Service providers are the central place to configure your application. Your own application, as well as all of Laravel's core services are bootstrapped via service providers. Bootstrapping means registering things, including registering service container bindings, event listeners, middleware, and even routes.

    If the service container is something that allows you to define bindings and inject dependencies, then the service provider is the place where it happens.

Junior questions

11 questions
  1. Question 5
    Junior

    Which template engine does Laravel use?

    • Laravel
    Reveal answer

    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.

  2. Question 6
    Junior

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

    • Laravel
    Reveal answer

    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.

    foreach (Product::where('name', 'bar')->cursor() as $flight) {
      //do some stuff
    }
    
  3. Question 7
    Junior

    What is Service Container?

    • Laravel
    Reveal answer

    The Laravel service container is a tool for managing class dependencies and performing dependency injection.

  4. Question 8
    Junior

    What are artisan commands?

    • Laravel
    Reveal answer

    Artisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application for example:

    php artisan serve

    // To start Laravel project
    
  5. Question 9
    Junior

    Why are migrations necessary?

    • Laravel
    Reveal answer

    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.

  6. Question 10
    Junior

    How do you generate migrations?

    • Laravel
    Reveal answer

    Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. To create a migration, use: php artisan make:migration create_users_table

  7. Question 11
    Junior

    List some official packages of Laravel

    • Laravel
    Reveal answer

    Cashier - Laravel Cashier provides an expressive, fluent interface to Stripe's and Braintree's subscription billing services. Dusk - Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. Envoy - Laravel Envoy provides a clean, minimal syntax for defining common tasks you run on your remote servers. Horizon - Horizon provides a dashboard and code-driven configuration for your Laravel powered Redis queues. Passport - provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Scout - Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Socialite - a simple, convenient way to authenticate with OAuth providers using Laravel Socialite.

  8. Question 12
    Junior

    What is Eloquent Models?

    • Laravel
    Reveal answer

    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.

  9. Question 13
    Junior

    What is the Facade Pattern used for?

    • Laravel
    Reveal answer

    Facades provide a static interface to classes that are available in the application's service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. All of Laravel's facades are defined in the Illuminate\Support\Facades namespace. Consider:

    use Illuminate\Support\Facades\Cache;
    Route::get('/cache', function () {
      return Cache::get('key');
    });
    
  10. Question 14
    Junior

    Explain Migrations in Laravel

    • Laravel
    Reveal answer

    Laravel Migrations are like version control for the 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 the application’s database schema.

  11. Question 15
    Junior

    What are Laravel events?

    • Laravel
    Reveal answer

    Laravel event provides a simple observer pattern implementation, that allow to subscribe and listen for events in the application. An event is an incident or occurrence detected and handled by the program. Below are some events examples in Laravel: A new user has registered A new comment is posted User login/logout New product is added.