Top 50 Laravel Interview Questions and Answers 2025

Taaza Content Team

Looking to crack your next Laravel developer interview in 2025? Here are the top 50 Laravel interview questions with detailed answers, explanations, and real-world code examples. Perfect for freshers and experienced developers alike!


1. What is Laravel and what are its key features?

Answer:
Laravel is a popular open-source PHP framework used for web application development. It follows the MVC (Model-View-Controller) architecture and is known for its elegant syntax, robust features, and developer-friendly tools.

Key Features:

  • Eloquent ORM (Object-Relational Mapping)

  • Routing System

  • Blade Templating Engine

  • Artisan CLI

  • Middleware Support

  • Authentication and Authorization

  • Task Scheduling

Example:

// Route Example
Route::get('/users', [UserController::class, 'index']);

2. What is Middleware in Laravel?

Answer:
Middleware acts as a filter for HTTP requests entering your application. It helps in executing code before or after a request is handled by the controller.

Use Cases:

  • Authentication

  • Logging

  • CORS handling

Creating Middleware:

php artisan make:middleware CheckAge

Example:

// app/Http/Middleware/CheckAge.php
public function handle($request, Closure $next)
{
    if ($request->age <= 18) {
        return redirect('no-access');
    }
    return $next($request);
}

Register in Kernel.php:

protected $routeMiddleware = [
    'checkage' => \App\Http\Middleware\CheckAge::class,
];

Use in route:

Route::get('dashboard', function () {
    // ...
})->middleware('checkage'); 

3. What is Eloquent ORM in Laravel?

Answer:
Eloquent ORM is Laravel’s built-in ORM (Object-Relational Mapping) that provides a simple and elegant ActiveRecord implementation for working with the database.

Key Features:

  • Easy CRUD operations

  • Relationship support (one-to-many, many-to-many)

  • Query building

Example:

// Model
$user = User::find(1);
echo $user->name;

// Insert
$user = new User();
$user->name = 'John';
$user->email = 'john@example.com';
$user->save();

4. What are Laravel Service Providers?

Answer:
Service providers are the central place of all Laravel application bootstrapping. They register bindings in the service container and are responsible for loading configuration, registering services, events, etc.

Example: Registering a class in a service provider:

$this->app->bind('App\Contracts\PaymentInterface', 'App\Services\StripePayment');

Service providers are located in:

app/Providers/

5. What is Dependency Injection in Laravel?

Answer:
Dependency Injection is a design pattern used to inject class dependencies into a class via the constructor or method. Laravel automatically resolves dependencies via the service container.

Example:

class UserController extends Controller
{
    protected $userService;
    
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
}

Laravel will automatically inject the UserService class when UserController is instantiated.


6. What is the use of Laravel’s Artisan Command Line Tool?

Answer:
Artisan is Laravel's command-line interface. It provides several helpful commands for tasks like migration, seeding, cache clearing, and even creating controllers and models.

Common Commands:

php artisan list
php artisan make:controller UserController
php artisan make:model Post -m
php artisan migrate
php artisan serve

7. What is the difference between hasOne and belongsTo in Laravel?

Answer: Both are Eloquent relationship methods.

  • hasOne: The current model owns one instance of the related model.

  • belongsTo: The current model is owned by another model.

Example:

// User hasOne Profile
public function profile()
{
    return $this->hasOne(Profile::class);
}

// Profile belongsTo User
public function user()
{
    return $this->belongsTo(User::class);
}

8. What are Laravel Migrations and why are they useful?

Answer:
Migrations are a version control system for your database, allowing teams to define and share the application's database schema definition.

Benefits:

  • Track database changes

  • Share schema between developers

  • Easily rollback changes

Commands:

php artisan make:migration create_users_table
php artisan migrate
php artisan migrate:rollback

Example:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}

9. What is Laravel's Blade templating engine?

Answer:
Blade is Laravel's built-in templating engine. It allows you to write PHP code in your views with a cleaner syntax and provides control structures like @if, @foreach, etc.

Example:

<!-- welcome.blade.php -->
<h1>Hello, {{ $name }}</h1>

@foreach($users as $user)
    <p>{{ $user->name }}</p>
@endforeach

10. What are Laravel Events and Listeners?

Answer:
Events are a way to implement the Observer pattern in Laravel. They allow you to subscribe and listen to specific actions that occur in your app.

Example:

Create event:

php artisan make:event UserRegistered

Create listener:

php artisan make:listener SendWelcomeEmail

Register in EventServiceProvider:

protected $listen = [
    UserRegistered::class => [
        SendWelcomeEmail::class,
    ],
];


11. What is the difference between soft delete and hard delete in Laravel?

Answer:

  • Soft Delete: Records are not permanently removed from the database. Instead, a deleted_at timestamp is set.

  • Hard Delete: Records are permanently deleted from the database.

Soft Delete Example:

Add SoftDeletes trait:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {
    use SoftDeletes;
}

Post::find(1)->forceDelete();


12. What are Laravel Facades?

Answer:
Facades provide a static interface to classes in the service container. They make complex classes easier to use without manually instantiating them.

Example:

use Illuminate\Support\Facades\Cache;

Cache::put('key', 'value', 600);
$value = Cache::get('key');

Facades are defined in config/app.php and map to service container bindings.


13. What is CSRF protection in Laravel?

Answer:
CSRF (Cross-Site Request Forgery) is a security feature to prevent unauthorized actions on behalf of authenticated users.

Laravel automatically includes CSRF tokens in forms.

Example in Blade:

<form method="POST" action="/submit">
    @csrf
    <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

Verify middleware:

\App\Http\Middleware\VerifyCsrfToken


14. What is the difference between get(), first(), and find() in Eloquent?

Answer:

  • get(): Returns a collection of results.

  • first(): Returns first result of the query.

  • find(): Finds a record by primary key.

Examples:

User::where('status', 'active')->get();     // Collection
User::where('email', 'test@example.com')->first(); // Single object
User::find(1); // Find by ID

15. How do you use validation in Laravel?

Answer:
Laravel provides several ways to validate form inputs using the validate() method or a Form Request class.

Example:

public function store(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email|unique:users',
    ]);
}

16. What is the use of queues in Laravel?

Answer:
Queues in Laravel are used to defer time-consuming tasks, like sending emails or processing images, improving application performance.

Usage Flow:

  1. Create job

  2. Dispatch job

  3. Queue worker processes job

Create Job:

php artisan make:job SendWelcomeEmail

Dispatch:

SendWelcomeEmail::dispatch($user);

Run queue:

php artisan queue:work


17. What is Laravel Passport and when to use it?

Answer:
Laravel Passport is a package that provides a full OAuth2 server implementation for API authentication.

Use When:

  • You need secure API authentication

  • Mobile apps or third-party access

Steps:

composer require laravel/passport php artisan migrate php artisan passport:install

In User model:

use Laravel\Passport\HasApiTokens;

Register routes:

Passport::routes();


18. How to create and use custom helper functions in Laravel?

Answer:

  1. Create a helper file:
    app/helpers.php

          function format_price($price) {
              return '$' . number_format($price, 2);
          }

  1. Include helper in composer.json:

     "autoload": { "files": [ "app/helpers.php" ] }

  1. Run:

     composer dump-autoload

Usage:

echo format_price(1000); // $1,000.00


19. What is the difference between include, extends, and yield in Blade?

Answer:

  • @include: Inserts another Blade file.

  • @extends: Defines a layout that the current view should inherit.

  • @yield: Placeholder for content to be injected.


20. What are Laravel Collections?

Answer:
Collections are wrapper classes around arrays that provide a fluent, convenient interface for working with data.

Common Methods:

  • map()

  • filter()

  • pluck()

  • sort()

  • reduce()

Example:

$users = collect([1, 2, 3, 4]);

$filtered = $users->filter(function ($value) {
    return $value > 2;
});

$filtered->all(); // [3, 4]

21. How does Laravel handle file uploads?

Answer:
Laravel makes file uploads easy using the Request object.

Example:

public function upload(Request $request)
{
    $request->validate([
        'image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
    ]);

    $file = $request->file('image');
    $filename = time() . '.' . $file->getClientOriginalExtension();
    $file->move(public_path('uploads'), $filename);

    return back()->with('success', 'File uploaded!');
}


22. What is route model binding in Laravel?

Answer:
Route model binding allows automatic injection of model instances based on route parameters.

Example:

Route::get('/user/{user}', function (User $user) {
    return $user->email;
});

Here, Laravel will automatically fetch the user by ID.


23. What is the Repository Pattern in Laravel?

Answer:
The Repository Pattern is a way to abstract the data layer, separating business logic from database queries.

Benefits:

  • More testable code

  • Separation of concerns

  • Cleaner controller

Example Interface:

interface UserRepositoryInterface {
    public function getAll();

 

Implementation:

class UserRepository implements UserRepositoryInterface {
    public function getAll() {
        return User::all();
    }
}

Bind in AppServiceProvider.


24. What is Laravel Sanctum?

Answer:
Sanctum is a lightweight API authentication system for SPAs and mobile apps.

Use for:

  • Token-based APIs

  • SPA authentication (Vue/React)

Basic Setup:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Use in model:

use Laravel\Sanctum\HasApiTokens;

25. What are observers in Laravel?

Answer:
Observers listen to model events such as created, updated, deleted, etc.

Create Observer:


 

bash

php artisan make:observer UserObserver --model=User

Example:

public function created(User $user) {
    Log::info('New user created: ' . $user->email);

 

Register in AppServiceProvider.


26. How does Laravel handle sessions?

Answer:
Laravel supports various session drivers: file, cookie, database, redis.

Session Usage:

// Store
session(['key' => 'value']);

// Retrieve
$value = session('key');

// Remove
session()->forget('key');

27. How do you implement localization in Laravel?

Answer:
Localization is used to support multiple languages in Laravel apps.

Steps:

  1. Store translations in resources/lang/en, resources/lang/fr, etc.

  2. Use Lang::get() or __() helper.

Example:

// resources/lang/en/messages.php
return [
    'welcome' => 'Welcome!',
];

// Usage
{{ __('messages.welcome') }}

28. How to handle exceptions in Laravel?

Answer:
Laravel uses App\Exceptions\Handler to manage exceptions.

Custom Handling:

public function render($request, Throwable $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

    return parent::render($request, $exception);
}

29. How to use Laravel's job batching feature?

Answer:
Job batching lets you group multiple jobs and track their completion.

Example:

Bus::batch([
    new ProcessPodcast($podcast),
    new OptimizePodcast($podcast),
])->dispatch();

Use then(), catch(), finally() for callbacks.


30. How do you use Laravel Scout?

Answer:
Laravel Scout provides a simple driver-based solution for full-text search.

Example with Meilisearch/Algolia:

composer require laravel/scout
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

In Model:

use Laravel\Scout\Searchable;

class Post extends Model {
    use Searchable;
}

Search:

Post::search('Laravel')->get();


31. How does Laravel handle caching?

Answer:
Laravel supports caching with drivers like file, database, Redis, etc.

Usage:

Cache::put('key', 'value', 600);
Cache::get('key');
Cache::forget('key');

Tagged Cache:

Cache::tags(['users'])->put('user:1', $user);


32. What are Laravel policies and gates?

Answer:
Laravel provides authorization mechanisms via policies and gates.

  • Gate: Closures to authorize actions.

  • Policy: Class-based approach.

Gate Example:

Gate::define('edit-post', function ($user, $post) {
    return $user->id === $post->user_id;
});

Policy Example:

php artisan make:policy PostPolicy --model=Post 

33. What is Laravel Mix?

Answer:
Laravel Mix is a wrapper around Webpack for compiling CSS/JS assets.

Example:

// webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')

Compile:

npm run dev


34. What is event broadcasting in Laravel?

Answer:
Event broadcasting allows real-time communication using WebSockets (e.g. with Pusher or Laravel Echo).

Steps:

  1. Create Event with implements ShouldBroadcast.

  2. Configure broadcasting.

  3. Listen on frontend using Echo.


35. What are Laravel collections macros?

Answer:
You can add custom methods to the collection class using macros.

Example:

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return strtoupper($value);
    });
})

Use:

collect(['a', 'b'])->toUpper(); // ['A', 'B']


36. How do you define constants in Laravel?

Answer:
You can define constants in:

  • .env file

  • config/constants.php (custom config file)

Usage:

// .env
APP_MODE=PRODUCTION

// config/constants.php
return [
    'APP_VERSION' => '1.0.0',
];

// Usage
config('constants.APP_VERSION');

37. What is the difference between php artisan serve and setting up a virtual host?

Answer:

  • php artisan serve: Quick way to run Laravel using PHP’s built-in server (for development).

  • Virtual Host: Used in Apache/Nginx for custom domain in local environment.

Use artisan serve only for quick local testing.


38. What is the purpose of php artisan config:cache?

Answer:
php artisan config:cache is used to combine all configuration files into one cached file, improving performance.

Use this in production after updating .env or config files.


39. How can you schedule tasks in Laravel?

Answer:
Laravel's Task Scheduler lets you schedule Artisan commands.

Define in app/Console/Kernel.php:

$schedule->command('emails:send')->dailyAt('13:00');

Run scheduler:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1


40. How do you implement API rate limiting in Laravel?

Answer:
Laravel provides built-in rate limiting using the throttle middleware.

Example:

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

This limits to 60 requests per minute.


41. What is a Service Provider in Laravel?

Answer:
Service Providers are the central place for bootstrapping application services. They are responsible for binding classes into the service container, registering events, middleware, and configuration.

Default Location:
app/Providers/

Key Methods:

  • register(): Bind services to the container.

  • boot(): Perform post-registration tasks.

Example:

public function register()
{
    $this->app->bind('MyService', function () {
        return new \App\Services\MyService();
    });
}

Register in config/app.php:

'providers' => [ App\Providers\MyServiceProvider::class, ],


42. What is the Service Container in Laravel?

Answer:
The Service Container is a powerful dependency injection container used for managing class dependencies and performing dependency injection.

Basic Binding:

app()->bind('App\Contracts\PaymentGateway', 'App\Services\StripePayment');

Automatic Resolution:

public function __construct(PaymentGateway $gateway) {
    $this->gateway = $gateway;
}

You can resolve any class with:

app(PaymentGateway::class);


43. What is Laravel Echo and when to use it?

Answer:
Laravel Echo is a JavaScript library for listening to server-side events broadcast by Laravel via WebSockets.

Use for:

  • Real-time chat

  • Notifications

  • Live updates

Frontend:

Echo.channel('orders')
    .listen('OrderShipped', (e) => {
        console.log(e.order);
    });

44. What is the difference between hasOne and belongsTo in Eloquent relationships?

Answer:

  • hasOne: The parent model has one related model.

  • belongsTo: The child model belongs to a parent.

Example:

// User.php
public function profile() {
    return $this->hasOne(Profile::class);
}

// Profile.php
public function user() {
    return $this->belongsTo(User::class);
}

45. How do you use Middleware in Laravel?

Answer:
Middleware filters HTTP requests before reaching the controller.

Create Middleware:

php artisan make:middleware CheckAge

Use:

Route::get('/restricted', function () { // ... })->middleware('check.age');

Global or route-specific middleware is registered in Kernel.php.


46. What is Lazy vs Eager Loading in Laravel?

Answer:

  • Lazy Loading: Related data is loaded on-demand.

  • Eager Loading: Related data is loaded with the initial query.

Example:

// Lazy
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name;
}

// Eager
$posts = Post::with('user')->get();

Eager loading is faster and avoids N+1 query issues.


47. What are Accessors and Mutators in Laravel?

Answer:

  • Accessors: Format data when retrieving.

  • Mutators: Format data before saving.

Example:

// Accessor
public function getNameAttribute($value) {
    return ucfirst($value);
}

// Mutator
public function setPasswordAttribute($value) {
    $this->attributes['password'] = bcrypt($value);
}

48. What is the use of with() and load() in Eloquent?

Answer:

  • with(): Eager loads before query execution.

  • load(): Eager loads after model has been retrieved.

Example:

Post::with('comments')->get(); // with()
$post->load('comments');       // load()


49. What is Laravel’s tap() helper function?

Answer:
tap() is used to perform actions on a value and return it.

Example:

$user = tap(User::first(), function ($user) {
    $user->update(['last_login' => now()]);
});

Returns the user after executing callback.


50. What is the purpose of the boot() method in a service provider?

Answer:
The boot() method is called after all other service providers have been registered. It is used to perform actions like:

  • Registering routes

  • Event listeners

  • Publishing config files

Example:

public function boot()
{
    view()->composer('*', function ($view) {
        $view->with('appName', config('app.name'));
    });
}

 

Stay Updated!

Would you like to receive notifications when we publish new blogs?