1. How can you assign Middleware to a specific route?

To assign middleware to a specific route, there is a middleware method that can be invoked when the defining the route.

use App\Http\Middleware\Authenticate;

Route::get('/user', [UserController::class])->middleware(Authenticate::class);

It also can accept an array of middleware names.

2. What is Eloquent?

Eloquent is an ORM (object-relational mapper) that helps a developer to interact with a database. Eloquent provides a Model that is mapped to a specific table and is used to insert, update, retrieve and delete records from the table.

3. What is the templating engine used by Laravel?

Laravel uses Blade as a templating engine. Blade is a powerful templating engine that doesn't restrict from using PHP code in the templates. All Blade templates are compiled into plain PHP code and cached until they are modified. Blade templates are using .blade.php extension and are stored in the resources/views directory.

4. What is an Artisan?

Laravel has a command line interface called Artisan. Artisan provides a number of helpful commands that can assist while building the Laravel application.

5. What is a Service Container?

Service Container is a one of the most important piece of the Laravel framework. The Service Container manages and it is responsible for the class dependencies and helps the developer to perform dependency injection. Dependency injection is simply "injecting" the class dependencies into the class.

6. Explain what Accessors and Mutators are.

Accessor is a method in Eloquent model that helps you to transform the model's attribute when retrieving the attribute. To define an Accessor, the method name for accessing the attribute should be a "camel case" representation of the column in the database. The method returns an Attribute instance that determine how the attribute will be accessed and mutated. To define how the attribute will be accessed, provide a get method

Similary as to an Accessor, a Mutator is method in Eloquent model that helps you transform the model's attribute when setting the attribute value. When defining the attribute, add a set argument. For example, let's change how the book author name is retrieved and set.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Interact with the user's first name.
     */
    protected function authorName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucwords($value),
            set: fn (string $value) => ucwords($value),
        );
    }
}

7. What is dd() function in Laravel?

The helper function dd() dumps the supplied variables and ends execution of the script. There is also the dump() function that also dumps the supplied variables but it doesn't halt the execution of the script.

8. How can you set Laravel applications in maintenance mode?

Enabling maintenance mode can be done via the following commands:

php artisan down

To disable the maintenance mode it can be done via:

php artisan up

9. Name a few official packages in Laravel.

Some of the official packages in Laravel are Breeze, Dusk, Homestead, Passport, Sanctum, Valet.

10. How can you implement soft delete in Laravel?

Soft delete flags data as deleted but it still remains visible or active in the database. In the Eloquent model there needs to have a deleted_at timestamp column, with a default value of null. To implement soft delete, add Illuminate\Database\Eloquent\SoftDeletes to the Eloquent model. To retrieve the deleted data to the user, use withTrashed() method:

Book:withTrashed()->get();

11. Name some common Artisan commands in Laravel.

Create Eloquent Model

php artisan make:model Book

Create Controller

php artisan make:controller BookController

Create migration

php artisan make:migration create_books_table

Display list of all the routes

php artisan route:list

Start Laravel Tinker

php artisan tinker

Start Laravel development server

php artisan serve

List artisan commands

php artisan list

12. What is a Laravel Collection?

Laravel's Collection is a wrapper for arrays. It provides useful and powerful functions to modify and manipulate data arrays.

13. What are migrations and how are used?

Migration is a Laravel feature that allows the developer to modify the application's database schema. Migrations act like version control for the database. You can use migrations to add and modify tables and create and modify columns.

14. How to retrieve data between two dates using query in Laravel?

Let's say we want to retrieve tasks that were created between 01 February and 30 March of 2023:

$startDate = Carbon::createFromFormat('Y-m-d', '2023-02-01');
$endDate = Carbon::createFromFormat('Y-m-d', '2022-03-30');
$result = Task::whereBetween('created_at', [$startDate, $endDate])->get();

15. Explain Seeders in Laravel.

Seeders in Laravel allows you to quickly insert data in your database. Laravel provides a Database seeder class. All seed classes are stored in database/seeders directory. The Seeder class has one method run.

16. List some aggregate method provide by Query Builder in Laravel.

Some of the aggregate methods that the Query Builder provides are: max(), min(), count(), avg() and sum().

17. What do you know about Laravel Contracts?

Laravel Contracts are set of interfaces of Laravel framework. They provide core services. Unlike Laravel Facades, the Contracts aren't required in your class constructor, they allow you to define explicit dependencies for your classes.

18. What is a Service Provider?

Service Provide is used to register Services, Events and etc in Laravel application before booting the application. The register method binds Classes and Services to Service Container. After the application includes all the dependencies in the Service Container, the boot method is executed.

19. What are Facades in Laravel?

Facades in Laravel allows the developer to access the classes inside the Service Container. They act as a static interface and provide a way to access complex objects and methods. Laravel provides a number of predefined Facades, like App, Auth, Blade, Cache, DB and many more. All of the Laravel's facades are defined in Illuminate\Support\Facades namespace.

20. What are the Relationships that Laravel supports?

Eloquent model defines Relationships as methods. These are the types of relationships that Laravel supports:

  • One To One Relationship
  • One To Many Relationship
  • Many To Many Relationship
  • Has One Of Many Relationship
  • HasOneThrough and hasManyThrough Relationship
  • Polymorphic Relationships

21. Explain Factories in Laravel.

Factories in Laravel allows you to build fake data for your models. This can be beneficial for testing and seeding data into the database. Factories will create rows in the database table and insert value to each row.

22. Name the default route files in Laravel.

All routes are defined in the routes directory. The routes/web.php file defines routes for your web. The routes in the routes/api.php are stateless and set in the API middleware group.

23. Explain Logging in Laravel.

Logging in Laravel provides easy-to-use logging system that allows you to write log messages to files, the system error log, Slack and more. It can be a powerful tool for testing and debugging. Laravel logging has channels that provides a specific way of writing log information. The underlying library the Laravel logging uses is the Monolog library.

24. Which is the REPL used in Laravel?

REPL is abbreviation for Read-Eval-Print-Loop. It's a type of interactive shell that takes single user inputs, process them and then it returns the result to the user. Laravel Tinker is a powerful REPL tool that is used to interact via command line with the Laravel application.

25. How can you exclude Middleware?

Beside assigning Middleware, you could also exclude Middleware, mainly in route groups, to prevent the Middleware applied to that specific route. For example:

Route::middleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/', [ProfileController::class, 'index']);

    Route::get('/profile', [ProfileController::class, 'profile'])->withoutMiddleware([EnsureTokenIsValid::class]);
});
  1. What are Events in Laravel?

Events are defined in app/Events directory. Event is an action that occurred that allows you to subscribe to and listen to. One Event could have multiple Listeners, that are stored in app\Listeners. For example, you would want to send an email, every time a user logs in. In this case, you can create an event UserLoggedIn which can be dispatched after the user logs in. Then a Listener, that listens to UserLoggedIn event would be triggered, and thus can send an email.

27. What are route groups?

If you need to share route attributes with multiple routes you can use the route groups. The route groups allow you to share middleware with multiple routes without the need to define attributes for each route. For example:

Route::middleware(['user', 'creator'])->group(function () {
    Route::get('/', function () {
        // Uses user & creator middleware...
    });

    Route::get('/user/profile', function () {
        // Uses user & creator middleware...
    });
});

28. Define a middleware that allows only a specific user type, creator to access the route for generating books.

Route::put('/books/create', [BookController::class, 'create'])->middleware('role:create');