23+ Laravel Interview Questions (Answered) You Should Know 
Tags: laravel, career, interview
Published: 2020-01-08 04:21:04

---
title: 23+ Laravel Interview Questions (Answered) You Should Know 
published: true
description: 23+ Laravel Interview Questions (ANSWERED) You Should Know 
tags: #laravel #career #interview
canonical_url: https://www.fullstack.cafe/blog/laravel-interview-questions
cover_image: https://images.pexels.com/photos/1769553/pexels-photo-1769553.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500
---

Despite what people like to think about PHP, it is still the most dominant server-side language on the web and Laravel is the most popular framework for PHP. According to ZipRecruiter, the average Laravel programmer salary is $83,000 per year in USA. Have a seat and explore the top 20 Laravel interview questions you should know before your next tech interview.

> Originally published on [FullStack.Cafe - Real Tech Interview Questions And Answers For Devs](https://www.fullstack.cafe/blog/laravel-interview-questions)

### Q1: What is the Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐

**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.

🔗 **Source:** [codingcompiler.com](https://codingcompiler.com/laravel-interview-questions-answers/)
### Q2: What are some benefits of Laravel over other Php frameworks?
> Topic: **Laravel**<br/>Difficulty: ⭐

* 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

🔗 **Source:** [mytectra.com](https://www.mytectra.com/interview-question/laravel-interview-questions-and-answers/)
### Q3: Explain Migrations in Laravel
> Topic: **Laravel**<br/>Difficulty: ⭐⭐

**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.

🔗 **Source:** [laravelinterviewquestions.com](http://www.laravelinterviewquestions.com/laravel-interview-questions-and-answers/page/4#sthash.pQAzAunW.dpbs)
### Q4: What is the Facade Pattern used for?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐

**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:
```js
use Illuminate\Support\Facades\Cache;

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

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.6/facades)
### Q5: What is Service Container?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐

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

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.7/eloquent#query-scopes)
### Q6: What is Eloquent Models?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐

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.

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.7/eloquent)
### Q7: What are Laravel events?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐

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.

🔗 **Source:** [mytectra.com](https://www.mytectra.com/interview-question/laravel-interview-questions-and-answers/)
### Q8: What do you know about query builder in Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.7/queries#raw-expressions)
### Q9: How do you generate migrations?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

```sh
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.

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.7/migrations)
### Q10: How do you mock a static facade methods?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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. 

```js
// actual code
$value = Cache::get('key');

// testing
Cache::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');
```

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.7/mocking)
### Q11: What is the benefit of eager loading, when do you use it?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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.

🔗 **Source:** [FullStack.Cafe](https://www.fullstack.cafe)
### Q12: How do you do soft deletes?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

```js
class User extends Model {
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }
}
```
Usage: 
```js
$users = User::popular()->women()->orderBy('created_at')->get();
```

Sometimes you may wish to define a scope that accepts parameters. **Dynamic scopes** accept query parameters:
```js
class User extends Model {
    public function scopeOfType($query, $type)
    {
        return $query->whereType($type);
    }
}
```
Usage:
```js
$users = User::ofType('member')->get();
```

🔗 **Source:** [laravel.com](https://laravel.com/docs/5.0/eloquent#query-scopes)
### Q13: What are named routes in Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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:

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

You can specify route names for controller actions:

```js
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:

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

// Generating Redirects...
return redirect()->route('profile');
```


🔗 **Source:** [laravelinterviewquestions.com](http://www.laravelinterviewquestions.com/laravel-interview-questions-and-answers/page/10#sthash.6MpaOmkG.dpbs)
### Q14: What is Closure in Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

```js
function handle(Closure $closure) {
    $closure('Hello World!');
}

handle(function($value){
    echo $value;
});
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/47348081/what-is-closure-in-laravel)
### Q15: List some Aggregates methods provided by query builder in Laravel ?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

🔗 **Source:** [laravelinterviewquestions.com](http://www.laravelinterviewquestions.com/laravel-interview-questions-and-answers/page/3#sthash.Pa7vkxua.dpbs)
### Q16: What is reverse routing in Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐

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

```js
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.

```js
{{ HTML::link_to_action('users@login') }}
```
It will create a link like http://mysite.com/login in view.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/30287896/rollback-one-specific-migration-in-laravel)
### Q17: Let's create Enumerations for PHP. Prove some code examples.
> Topic: **PHP**<br/>Difficulty: ⭐⭐⭐

And what if our code require more validation of enumeration constants and values?

---
Depending upon use case, I would normally use something simple like the following:

```php
abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

$today = DaysOfWeek::Sunday;
```

Here's an expanded example which may better serve a much wider range of cases:

```php
abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect - > getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);
        }

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);
    }

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);
    }
}
```
And we could use it as:
```php
abstract class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/254514/php-and-enumerations)
### Q18: What is autoloading classes in PHP?
> Topic: **PHP**<br/>Difficulty: ⭐⭐⭐

With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error.

The `spl_autoload_register()` function in PHP can register any number of autoloaders, enable classes and interfaces to autoload even if they are undefined.

```php
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2(); 
```

In the above example we do not need to include Class1.php and Class2.php. The `spl_autoload_register()` function will automatically load Class1.php and Class2.php.

🔗 **Source:** [github.com/Bootsity](https://github.com/Bootsity/cracking-php-interviews-book)
### Q19: Does PHP support method overloading?
> Topic: **PHP**<br/>Difficulty: ⭐⭐⭐

**Method overloading** is the phenomenon of using same method name with different signature. You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. 

You can, however, declare a **variadic function** that takes in a variable number of arguments. You would use `func_num_args()` and `func_get_arg()` to get the arguments passed, and use them normally.

```php
function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));
    }
}

/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);
```

🔗 **Source:** [github.com/Bootsity](https://github.com/Bootsity/cracking-php-interviews-book)
### Q20: Why do we need Traits in Laravel?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐⭐

**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.
 
```js
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";
```
     

🔗 **Source:** [conetix.com.au](https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5)
### Q21: What is Autoloader in PHP?
> Topic: **Laravel**<br/>Difficulty: ⭐⭐⭐⭐

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.

🔗 **Source:** [sitepoint.com](https://www.sitepoint.com/battle-autoloaders-psr-0-vs-psr-4/)
### Q22: What does yield mean in PHP?
> Topic: **PHP**<br/>Difficulty: ⭐⭐⭐⭐

Explain this code and what the `yield` does:
```php
function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}
```

---
The `yield` keyword returns data from a generator function. A generator function is effectively a more compact and efficient way to write an `Iterator`. It allows you to define a function that will calculate and return values while you are looping over it.

So the function in the question is almost the same as this one without:
```php
function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}
```
With only one difference that `a()` returns a `generator` and` b()` just a simple `array`. You can iterate on both. 

The generator version of the function does not allocate a full array and is therefore less memory-demanding. Generators can be used to work around memory limits. Because generators compute their _yielded_ values only on demand, they are useful for representing sequences that would be expensive or impossible to compute at once.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/17483806/what-does-yield-mean-in-php)
### Q23: What does a $$$ mean in PHP? 
> Topic: **PHP**<br/>Difficulty: ⭐⭐⭐⭐⭐

A syntax such as `$$variable` is called Variable Variable. Let's give the `$$$` a try:

```php
$real_variable = 'test';
$name = 'real_variable'; // variable variable for real variable
$name_of_name = 'name'; // variable variable for variable variable

echo $name_of_name . '<br />';
echo $$name_of_name . '<br />';
echo $$$name_of_name . '<br />';
```
And here's the output :
```
name
real_variable
test
```

🔗 **Source:** [guru99.com](https://stackoverflow.com/questions/2715654/what-does-dollar-dollar-or-double-dollar-mean-in-php)

> *Thanks 🙌 for reading and good luck on your interview!* <br/>*Please share this article with your fellow devs if you like it!* <br/>*Check more FullStack Interview Questions & Answers on 👉 [www.fullstack.cafe](https://www.fullstack.cafe)*