Top 50 Laravel Interview Questions and Answers (Part 1: Fundamentals)

Published on December 05, 2025
Laravel InterviewQuestions PHP WebDevelopment LaravelInterview Programming BackendDevelopment LaravelTutorial

Introduction

Preparing for a Laravel developer interview? Whether you're a junior developer looking for your first Laravel role or a senior developer brushing up on fundamentals, this comprehensive guide covers the top 50 Laravel interview questions you're likely to encounter. In Part 1, we focus on the absolute fundamentals - the questions that form the foundation of every Laravel interview.

Laravel Fundamentals: The Core Concepts

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

Answer: Laravel is a free, open-source PHP web framework created by Taylor Otwell, following the model-view-controller (MVC) architectural pattern. Its main features include:

  • Elegant syntax and expressive code structure
  • Built-in authentication and authorization
  • Eloquent ORM for database operations
  • Blade templating engine
  • Artisan command-line interface
  • Database migrations and seeding
  • Built-in testing capabilities
  • Task scheduling and job queues
  • Extensive package ecosystem

2. Explain Laravel's MVC architecture

Answer: Laravel follows the Model-View-Controller pattern:

  • Models represent your data structures and business logic (typically Eloquent models)
  • Views are the presentation layer (Blade templates)
  • Controllers handle user requests, process data using models, and return views

Example flow: User request → Route → Controller → Model → View → Response

3. What is Composer and why is it important in Laravel?

Answer: Composer is a dependency manager for PHP that Laravel uses to manage packages and dependencies. It's crucial because:

  • Manages all Laravel framework dependencies
  • Handles autoloading of classes
  • Allows easy installation of packages via Packagist
  • Enables version control for dependencies

4. How do you install Laravel?

Answer: There are several ways:

# Using Composer create-project
composer create-project laravel/laravel project-name

# Using Laravel Installer
composer global require laravel/installer
laravel new project-name

# Using Laravel Sail (with Docker)
curl -s https://laravel.build/example-app | bash

5. Explain the Laravel directory structure

Answer: Key directories in a Laravel project:

  • app/ - Application core (Models, Controllers, Middleware)
  • bootstrap/ - Application bootstrapping and cache
  • config/ - Configuration files
  • database/ - Migrations, seeders, factories
  • public/ - Web server entry point, assets
  • resources/ - Views, raw assets (CSS, JS), language files
  • routes/ - Route definitions
  • storage/ - Compiled Blade templates, logs, cache, sessions
  • tests/ - PHPUnit test files
  • vendor/ - Composer dependencies

6. What is the .env file in Laravel?

Answer: The .env file is an environment configuration file that stores sensitive and environment-specific settings:

  • Database credentials
  • API keys and secrets
  • Application environment (local, production, staging)
  • Mail server configuration
  • Cache and session drivers

Never commit this file to version control

7. How do you create and use environment variables?

Answer: Add variables to .env file:

DB_HOST=localhost
DB_DATABASE=myapp
API_KEY=your_secret_key_here

Access them in your code:

// Using env() helper
$dbHost = env('DB_HOST', 'default_value');

// Using config() helper (after publishing to config)
$apiKey = config('services.api.key');

8. What is Service Container in Laravel?

Answer: The Service Container is Laravel's dependency injection container that manages class dependencies and performs dependency injection. It's the heart of Laravel's architecture:

  • Binds interfaces to concrete implementations
  • Resolves dependencies automatically
  • Enables dependency injection throughout the application

9. Explain Service Providers in Laravel

Answer: Service Providers are the central place for Laravel application bootstrapping. They:

  • Register services in the service container
  • Bootstrap services (database, queue, etc.)
  • Register routes, views, and migrations
  • Are configured in config/app.php under providers

10. What are Facades in Laravel?

Answer: Facades provide a "static" interface to classes in the service container. They're essentially syntactic sugar that provides expressive syntax while maintaining testability. Common facades include:

  • Cache:: for caching
  • DB:: for database operations
  • Auth:: for authentication
  • Route:: for routing

11. What is Middleware in Laravel?

Answer: Middleware provides a mechanism for filtering HTTP requests entering your application. Examples:

  • Authentication middleware
  • CSRF protection
  • Logging requests
  • CORS handling
  • Maintenance mode

12. How do you create custom middleware?

Answer:

php artisan make:middleware CheckAge

Then implement in app/Http/Middleware/CheckAge.php:

public function handle($request, Closure $next)
{
    if ($request->age <= 18) {
        return redirect('home');
    }
    return $next($request);
}

Register in app/Http/Kernel.php:

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

13. Explain Laravel Routing

Answer: Routing maps URLs to controller actions. Basic routes in routes/web.php:

// Basic route
Route::get('/hello', function () {
    return 'Hello World';
});

// Route with controller
Route::get('/user/{id}', [UserController::class, 'show']);

// Named route
Route::get('/profile', function () {
    // ...
})->name('profile');

// Route groups with middleware
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index');
});

14. What are Named Routes and why use them?

Answer: Named routes allow you to generate URLs without hardcoding them:

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

// Using
$url = route('profile');
return redirect()->route('profile');
<a href="{{ route('profile') }}">Profile</a>

Benefits: Easier maintenance, consistent URLs throughout the app.

15. Explain Route Parameters

Answer: Route parameters capture segments of the URI:

// Required parameter
Route::get('/user/{id}', function ($id) {
    return 'User '.$id;
});

// Optional parameter
Route::get('/user/{name?}', function ($name = 'Guest') {
    return $name;
});

// Regular expression constraints
Route::get('/user/{id}', function ($id) {
    // ...
})->where('id', '[0-9]+');

16. What is Route Model Binding?

Answer: Route Model Binding automatically injects model instances into your routes:

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

// Explicit binding (in RouteServiceProvider)
public function boot()
{
    parent::boot();
    
    Route::model('user', User::class);
}

17. How do you create a controller in Laravel?

Answer:

php artisan make:controller UserController

Basic controller structure:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users.index', ['users' => $users]);
    }
    
    public function show($id)
    {
        $user = User::find($id);
        return view('users.show', compact('user'));
    }
}

18. What is Resource Controller?

Answer: Resource controllers handle all CRUD operations for a resource:

php artisan make:controller PhotoController --resource

Creates methods: index, create, store, show, edit, update, destroy

Register with:

Route::resource('photos', PhotoController::class);

19. Explain Dependency Injection in Laravel

Answer: Dependency Injection is a technique where dependencies are "injected" into classes rather than created within them:

public function __construct(UserRepository $users)
{
    $this->users = $users;
}

// Laravel automatically resolves and injects UserRepository

20. What are Laravel Collections?

Answer: Collections are object-oriented arrays with powerful methods for processing data:

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

// Chaining methods
$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
})->map(function ($item) {
    return $item * 2;
});

21. Explain Blade Templating Engine

Answer: Blade is Laravel's simple yet powerful templating engine. Key features:

  • Template inheritance with @extends and @yield
  • Sections with @section and @show
  • Control structures: @if, @foreach, @for
  • Includes with @include
  • Components with @component or <x-component>

22. How do you pass data to Blade views?

Answer: Multiple ways to pass data:

// Using with() method
return view('greeting')->with('name', 'Victoria');

// Using compact()
$name = 'Victoria';
return view('greeting', compact('name'));

// Array as second parameter
return view('greetings', ['name' => 'Victoria']);

// Using with() chaining
return view('greeting')
    ->with('name', 'Victoria')
    ->with('occupation', 'Developer');

23. What are Blade Directives?

Answer: Blade directives are special syntax for common PHP operations:

{{-- Display escaped data --}}
Hello, {{ $name }}

{{-- Unescaped data (use with caution) --}}
{!! $htmlContent !!}

{{-- If statements --}}
@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

{{-- Loops --}}
@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

{{-- Includes --}}
@include('shared.header')

24. What is CSRF Protection in Laravel?

Answer: Cross-Site Request Forgery (CSRF) protection prevents unauthorized commands from being executed on behalf of an authenticated user. Laravel automatically generates a CSRF token for each active user session.

In forms:

<form method="POST" action="/profile">
    @csrf
    <!-- Form fields -->
</form>

For APIs: Use VerifyCsrfToken middleware or include token in headers.

25. How does Laravel handle sessions?

Answer: Laravel provides a unified API for various session backends:

  • File (default for local development)
  • Cookie
  • Database
  • Redis
  • Memcached

Configuration in config/session.php:

// Storing data
session(['key' => 'value']);
// or
Session::put('key', 'value');

// Retrieving data
$value = session('key');
// or
$value = Session::get('key');

26. Explain Laravel's Authentication System

Answer: Laravel provides a complete authentication system out of the box:

  • User registration and login
  • Password reset
  • Email verification
  • "Remember me" functionality

Configured via Laravel Breeze, Jetstream, or manual setup

Basic usage:

// Login a user
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    // Authentication successful
}

// Get authenticated user
$user = Auth::user();

// Check if user is authenticated
if (Auth::check()) {
    // User is logged in
}

27. What are Laravel Gates and Policies?

Answer: Gates and Policies provide authorization mechanisms:

Gates (Closure-based):

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

// Using
if (Gate::allows('edit-post', $post)) {
    // The user can edit the post...
}

Policies (Class-based):

php artisan make:policy PostPolicy --model=Post

28. Explain Laravel Events and Listeners

Answer: Events and Listeners implement the observer pattern:

# Create event
php artisan make:event OrderShipped

# Create listener
php artisan make:listener SendShipmentNotification --event=OrderShipped
// Firing an event
event(new OrderShipped($order));

// Listener handles the event
class SendShipmentNotification
{
    public function handle(OrderShipped $event)
    {
        // Send notification...
    }
}

29. What are Laravel Notifications?

Answer: Notifications provide a simple way to send notifications via multiple channels (email, SMS, Slack, etc.):

php artisan make:notification InvoicePaid
// Sending
$user->notify(new InvoicePaid($invoice));

// Notification class defines channels and content
class InvoicePaid extends Notification
{
    public function via($notifiable)
    {
        return ['mail', 'database'];
    }
}

30. Explain Laravel Mail

Answer: Laravel provides a clean, simple API for sending email using SMTP, Mailgun, SparkPost, Amazon SES, or sendmail:

php artisan make:mail OrderShipped
// Sending email
Mail::to($request->user())
    ->send(new OrderShipped($order));

// Mailable class
class OrderShipped extends Mailable
{
    public function build()
    {
        return $this->view('emails.orders.shipped')
                    ->with([
                        'order' => $this->order,
                    ]);
    }
}

31. What is Laravel Artisan?

Answer: Artisan is Laravel's command-line interface that provides helpful commands for development:

Common commands:

php artisan make:model Product
php artisan make:controller ProductController
php artisan make:migration create_products_table
php artisan migrate
php artisan db:seed
php artisan tinker
php artisan route:list
php artisan storage:link

32. How do you create custom Artisan commands?

Answer:

php artisan make:command SendEmails
class SendEmails extends Command
{
    protected $signature = 'email:send {user} {--queue}';
    protected $description = 'Send emails to users';
    
    public function handle()
    {
        $userId = $this->argument('user');
        $queue = $this->option('queue');
        
        $this->info('Emails sent successfully!');
    }
}

33. Explain Laravel Helpers

Answer: Laravel includes many global helper functions:

  • app() - Get the application instance
  • config() - Get/set configuration values
  • route() - Generate URLs for named routes
  • url() - Generate absolute URLs
  • asset() - Generate URLs for assets
  • auth() - Get the authenticator instance
  • cache() - Get/set cache values
  • session() - Get/set session values
  • view() - Get a view instance

34. What is Laravel Tinker?

Answer: Tinker is a REPL (Read-Eval-Print Loop) for Laravel that allows interactive PHP sessions:

php artisan tinker

# In Tinker
>>> $user = new App\Models\User;
>>> $user->name = 'John';
>>> $user->email = 'john@example.com';
>>> $user->save();

35. Explain Laravel's Error and Exception Handling

Answer: Laravel uses Monolog for logging and provides custom error pages:

  • Configuration in config/app.php (debug option)
  • Custom exception handling in app/Exceptions/Handler.php
  • HTTP exceptions automatically return appropriate responses
  • Custom error pages in resources/views/errors/

36. What is Localization in Laravel?

Answer: Localization provides a convenient way to retrieve strings in multiple languages:

// Language files in resources/lang/{locale}/
// resources/lang/en/messages.php
return [
    'welcome' => 'Welcome to our application',
];

// Usage
echo __('messages.welcome');
echo trans('messages.welcome');

37. Explain Laravel's File Storage System

Answer: Laravel provides a unified filesystem API for local and cloud storage:

// Configuration in config/filesystems.php
Storage::disk('local')->put('file.txt', 'Contents');
Storage::disk('s3')->put('file.txt', 'Contents');

// Public disk (for user uploads)
Storage::disk('public')->put('avatars/1.jpg', $fileContents);

38. What are Laravel's Validation Rules?

Answer: Laravel provides powerful validation:

$validated = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
    'email' => 'required|email|unique:users',
    'password' => 'required|min:8|confirmed',
]);

// Custom error messages
$messages = [
    'required' => 'The :attribute field is required.',
    'email.unique' => 'This email is already taken.',
];

39. Explain Form Request Validation

Answer: Form Requests are custom request classes that handle validation:

php artisan make:request StorePostRequest
class StorePostRequest extends FormRequest
{
    public function authorize()
    {
        return true; // Or add authorization logic
    }
    
    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'body' => 'required',
        ];
    }
}

40. What are Accessors and Mutators in Eloquent?

Answer: Accessors and Mutators allow you to format Eloquent attribute values:

// Accessor (get)
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}
// Usage: $user->full_name

// Mutator (set)
public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = strtolower($value);
}
// Usage: $user->first_name = 'John';

41. Explain Eloquent Relationships

Answer: Eloquent relationships define relationships between database tables:

// One to One
public function phone()
{
    return $this->hasOne(Phone::class);
}

// One to Many
public function posts()
{
    return $this->hasMany(Post::class);
}

// Many to Many
public function roles()
{
    return $this->belongsToMany(Role::class);
}

42. What are Database Migrations?

Answer: Migrations are version control for your database schema:

php artisan make:migration create_users_table
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}

43. How do you run database migrations?

Answer:

# Run all outstanding migrations
php artisan migrate

# Rollback last migration
php artisan migrate:rollback

# Rollback all migrations
php artisan migrate:reset

# Rollback and migrate again
php artisan migrate:refresh

# Show migration status
php artisan migrate:status

44. What are Database Seeders?

Answer: Seeders populate your database with test data:

php artisan make:seeder UsersTableSeeder
class UsersTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')->insert([
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => bcrypt('password'),
        ]);
    }
}

// Run seeder
php artisan db:seed --class=UsersTableSeeder

45. Explain Eloquent Model Factories

Answer: Factories generate model instances with fake data:

php artisan make:factory PostFactory
class PostFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => $this->faker->sentence,
            'content' => $this->faker->paragraph,
            'user_id' => User::factory(),
        ];
    }
}

// Usage
Post::factory()->count(50)->create();

46. What is Eloquent Eager Loading?

Answer: Eager loading prevents the N+1 query problem:

// Without eager loading (N+1 queries)
$books = Book::all();
foreach ($books as $book) {
    echo $book->author->name; // Query executed here
}

// With eager loading (2 queries)
$books = Book::with('author')->get();
foreach ($books as $book) {
    echo $book->author->name; // Already loaded
}

47. Explain Laravel's Caching System

Answer: Laravel supports multiple cache drivers:

  • File
  • Database
  • Redis
  • Memcached
// Store in cache for 60 minutes
Cache::put('key', 'value', 60);

// Store if not exists
Cache::add('key', 'value', 60);

// Retrieve
$value = Cache::get('key');

// Retrieve or store
$value = Cache::remember('users', 60, function () {
    return DB::table('users')->get();
});

48. What are Laravel Queues?

Answer: Queues allow you to defer time-consuming tasks:

// Dispatch a job
ProcessPodcast::dispatch($podcast);

// Job class
class ProcessPodcast implements ShouldQueue
{
    public function handle()
    {
        // Process podcast...
    }
}

// Run queue worker
php artisan queue:work

49. Explain Task Scheduling in Laravel

Answer: Laravel's command scheduler allows you to schedule tasks:

// In app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('emails:send')->daily();
    $schedule->exec('node /home/forge/script.js')->daily();
    $schedule->job(new Heartbeat)->everyFiveMinutes();
}

// Cron entry on server
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

50. What is Laravel Mix?

Answer: Laravel Mix provides a fluent API for defining Webpack build steps:

// webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        require('tailwindcss'),
    ])
    .version();

Conclusion

Mastering these fundamental Laravel concepts will give you a strong foundation for any Laravel developer interview. Remember that understanding the "why" behind these features is just as important as knowing the "how." Practice implementing these concepts in real projects to solidify your understanding.

Key Takeaways:

  • Laravel's MVC architecture provides clean separation of concerns
  • Eloquent ORM makes database operations intuitive
  • Blade templating offers powerful features with simple syntax
  • Artisan commands accelerate development
  • Middleware provides flexible request/response handling
  • Service Container enables clean dependency injection

Next Steps:

In Part 2, we'll dive deeper into advanced Laravel concepts, including Eloquent relationships, testing, deployment strategies, and performance optimization.