Laravel Interview Questions with Practical Coding Examples
Ace your Laravel interview with 50+ real‑world questions and hands‑on code solutions — 2026 edition
🔍 Introduction
Laravel has become one of the most sought-after PHP frameworks in the industry. Whether you're a junior developer preparing for your first Laravel role or a seasoned developer looking to level up, practical knowledge is what sets you apart in interviews.
This guide brings together 50+ real interview questions with practical coding examples that you can actually run and understand. We cover everything from Eloquent ORM and Blade to queues, events, security, and testing. Each question is explained with clear code snippets and best practices.
🗄️ Eloquent ORM & Models
Eloquent is the heart of Laravel's database interaction. Expect questions on relationships, scopes, and performance.
Q1 How do you define a one-to-many relationship in Eloquent?
// User model (one)
public function posts()
{
return $this->hasMany(Post::class);
}
// Post model (many)
public function user()
{
return $this->belongsTo(User::class);
}
Q2 What is the N+1 query problem and how do you solve it?
The N+1 problem occurs when you retrieve data and then loop through it, making additional queries for each item. Solve it with eager loading using with().
// ❌ N+1 problem
$users = User::all();
foreach ($users as $user) {
echo $user->posts->count(); // executes N additional queries
}
// ✅ Eager loaded (only 2 queries)
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count();
}
Q3 What are Eloquent scopes and how do you use them?
Scopes allow you to encapsulate common query constraints. Define them in your model and reuse them.
// In User model
public function scopeActive($query)
{
return $query->where('active', 1);
}
public function scopeRecent($query)
{
return $query->orderBy('created_at', 'desc');
}
// Usage
$users = User::active()->recent()->get();
Q4 How do you handle soft deletes in Laravel?
Soft deletes allow you to "delete" records without removing them from the database. Use the SoftDeletes trait.
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
// Soft delete
$post->delete();
// Restore
$post->restore();
// Get only trashed
$posts = Post::onlyTrashed()->get();
// With trashed
$posts = Post::withTrashed()->get();
Q5 What is the difference between update() and save() on an Eloquent model?
save() is a method on the model instance that persists changes to the database. update() is a mass-assignment method that updates multiple attributes at once.
// save() - instance method
$user = User::find(1);
$user->name = 'John';
$user->save();
// update() - mass assignment
User::where('active', 1)->update(['status' => 'active']);
🛤️ Routing & Controllers
Routing is how Laravel maps HTTP requests to code. Here are key interview questions.
Q6 What is the difference between Route::get() and Route::match()?
Route::get() responds only to GET requests. Route::match() accepts an array of HTTP verbs.
Route::get('/profile', [ProfileController::class, 'show']);
Route::match(['get', 'post'], '/dashboard', [DashboardController::class, 'index']);
Q7 How do you pass parameters to routes?
Use curly braces in the URI and type-hint parameters in the controller method.
Route::get('/user/{id}', function ($id) {
return User::find($id);
});
Route::get('/post/{slug}', [PostController::class, 'show']);
// With optional parameter
Route::get('/user/{name?}', function ($name = null) {
return $name ?? 'Guest';
});
Q8 What is route model binding and how does it work?
Route model binding automatically injects the model instance based on the route parameter. Use Route::bind() or implicit binding.
// Implicit binding (Laravel resolves by ID)
Route::get('/post/{post}', [PostController::class, 'show']);
// In controller
public function show(Post $post)
{
return view('post.show', compact('post'));
}
// Custom binding
Route::bind('post', function ($value) {
return Post::where('slug', $value)->firstOrFail();
});
Q9 What are route groups and why use them?
Route groups allow you to share attributes (middleware, prefix, namespace) across multiple routes.
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/settings', [SettingsController::class, 'index']);
});
Route::prefix('admin')->namespace('Admin')->group(function () {
Route::get('/users', [UserController::class, 'index']);
});
🎨 Blade Templates
Blade is Laravel's powerful templating engine. Expect practical questions on directives and layouts.
Q10 What is the difference between @php and @raw?
@php executes PHP code inside Blade. @raw outputs raw HTML without escaping.
@php
$var = 'Hello';
@endphp
@raw(<div>Unescaped HTML</div>)
Q11 How do you use layouts and sections in Blade?
Use @extends, @section, and @yield to create reusable layouts.
<html>
<body>
@yield('content')
@yield('scripts')
</body>
</html>
@extends('layout')
@section('content')
<h1>Home Page</h1>
@endsection
@section('scripts')
<script>console.log('Loaded!');</script>
@endsection
Q12 What are Blade components and how are they different from sections?
Blade components are self-contained, reusable UI elements with their own logic and views. Sections are for content injection into layouts.
// App\View\Components\Alert.php
class Alert extends Component
{
public $type;
public $message;
public function render()
{
return view('components.alert');
}
}
// In Blade
<x-alert type="success" message="Saved!" />
Q13 How do you escape HTML in Blade?
Use {{ $variable }} for auto‑escaping, and {!! $variable !!} to output raw HTML without escaping.
{{ $user->name }} // Escaped
{!! $user->bio !!} // Raw HTML (use with caution)
🛡️ Middleware & Security
Q14 What is middleware and how do you create one?
Middleware acts as a filter for HTTP requests. Create one using php artisan make:middleware.
php artisan make:middleware CheckAge
// In CheckAge middleware
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
// Register in kernel
protected $routeMiddleware = [
'check.age' => \App\Http\Middleware\CheckAge::class,
];
// Apply to route
Route::get('/adult', [AdultController::class, 'index'])->middleware('check.age');
Q15 What is CSRF protection and how does Laravel handle it?
Laravel generates a CSRF token for every session and verifies it on POST/PUT/DELETE requests. Use @csrf in forms.
<form method="POST" action="/profile">
@csrf
<input type="text" name="name" />
<button type="submit">Update</button>
</form>
Q16 How do you secure API routes in Laravel?
Use Laravel Sanctum or Passport for API authentication, and apply auth:sanctum middleware.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
📦 Queues & Jobs
Q17 What are queues and when should you use them?
Queues defer time‑consuming tasks (email, image processing, API calls) to improve response times.
// Create a job
php artisan make:job SendWelcomeEmail
// In your controller
SendWelcomeEmail::dispatch($user);
// Job class
class SendWelcomeEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function handle()
{
Mail::to($this->user->email)->send(new WelcomeMail());
}
}
Q18 What is the difference between dispatch() and dispatchNow()?
dispatch() pushes the job to the queue; dispatchNow() runs it synchronously in the current request.
Q19 How do you handle failed jobs?
Use failed_jobs table, define failed() method, and use queue:retry command.
// In job class
public function failed($exception)
{
Log::error('Job failed: ' . $exception->getMessage());
}
// Retry failed jobs
php artisan queue:retry all
🔔 Events & Listeners
Q20 What are events and listeners in Laravel?
Events are signals that something happened; listeners are classes that respond to those events.
// Create event
php artisan make:event UserRegistered
// Create listener
php artisan make:listener SendWelcomeEmail --event=UserRegistered
// Event class
class UserRegistered
{
public $user;
public function __construct($user) { $this->user = $user; }
}
// Listener class
class SendWelcomeEmail
{
public function handle(UserRegistered $event)
{
Mail::to($event->user->email)->send(...);
}
}
// Fire event
event(new UserRegistered($user));
🧪 Testing & Debugging
Q21 How do you write a test for a controller in Laravel?
Use PHPUnit and Laravel's testing helpers.
public function test_user_can_view_dashboard()
{
$user = User::factory()->create();
$this->actingAs($user)
->get('/dashboard')
->assertStatus(200)
->assertSee('Welcome');
}
Q22 What is the difference between assertDatabaseHas() and assertDatabaseMissing()?
They check for the existence or absence of a record in the database matching a given array of criteria.
$this->assertDatabaseHas('users', ['email' => 'john@example.com']);
$this->assertDatabaseMissing('users', ['email' => 'old@example.com']);
⚙️ Service Providers & Facades
Q23 What is a service provider and when would you create one?
Service providers are the central place to register bindings, services, and events. Create one for custom services.
php artisan make:provider AnalyticsServiceProvider
// In register()
public function register()
{
$this->app->bind('analytics', function ($app) {
return new AnalyticsService();
});
}
// In boot()
public function boot()
{
View::composer('*', function ($view) {
$view->with('analytics', app('analytics'));
});
}
Q24 What are facades and when should you use them?
Facades provide a static interface to services in the container. Use them for readability and convenience.
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
Cache::put('key', 'value', 60);
Log::info('User logged in');
📡 API Development
Q25 How do you create a RESTful API in Laravel?
Use controllers that return JSON responses, and use API resources to transform data.
// In controller
public function index()
{
return UserResource::collection(User::paginate());
}
public function show($id)
{
return new UserResource(User::findOrFail($id));
}
// API routes
Route::apiResource('/users', UserController::class);
Q26 What is API rate limiting and how do you implement it?
Use Laravel's built-in rate limiter. Define in app/Http/Kernel.php or using RateLimiter::for().
// In App\Http\Kernel
protected $middlewareGroups = [
'api' => [
\Illuminate\Routing\Middleware\ThrottleRequests::class . ':60,1',
],
];
// Or using named rate limiter
RateLimiter::for('api', function ($job) {
return Limit::perMinute(100);
});
💼 Top Laravel Interview Q&A (with Code)
Click any question to reveal the answer with a practical code example.
📌 Key Takeaways for Your Laravel Interview
- Understand Eloquent relationships and eager loading to avoid N+1.
- Be able to explain middleware, service providers, and facades.
- Know the difference between queues and events, and when to use each.
- Practice writing tests — both unit and feature tests.
- Understand API development with resources and rate limiting.
- Be comfortable with Blade components and layout inheritance.
- Explain security features: CSRF, XSS prevention, validation.
- Show that you understand deployment and performance optimization.
- Always write clean, readable code — even in examples.
- Be prepared to discuss trade‑offs and when to use alternative approaches.
🚀 Ready to crush your Laravel interview? Practice these examples, understand the patterns, and you'll be well on your way. For personalized coaching, reach out to us at FreeLearning365.com@gmail.com.
0 Comments
thanks for your comments!