🚀 200+ Laravel Interview Questions & Answers 2026
From Beginner to Most Expert • AI-Driven Development • Business Problem Solving • Real-World Scenarios • Hands‑on Labs
📑 In This Epic Guide (200+ Items)
🌟 Beginner Laravel Interview Questions (50)
Build a rock‑solid foundation. These questions cover absolute basics and are asked in every junior role interview.
Beginner 1. What is Laravel and why is it so popular?
Laravel is an open‑source PHP web framework that follows the Model‑View‑Controller (MVC) architectural pattern. It was created by Taylor Otwell in 2011. Its popularity stems from its expressive, elegant syntax, rich set of built‑in features (routing, authentication, caching, queues, task scheduling), and a massive ecosystem (Forge, Vapor, Nova, Envoyer). Laravel simplifies common tasks and accelerates development, making it the top choice for modern PHP applications.
Beginner 2. Explain the MVC architecture in Laravel.
Model – Represents data and business logic. Usually extends Eloquent ORM, handles database interactions.
View – The presentation layer (Blade templates) that the user sees. It receives data from the controller and displays it.
Controller – Acts as an intermediary. It processes HTTP requests, retrieves/modifies data via models, and returns a view or JSON response.
Beginner 3. What is Composer, and how is it used in Laravel?
Composer is PHP’s dependency manager. Laravel uses it to manage all packages (the framework itself, third‑party libraries). Commands like composer create-project laravel/laravel scaffold a new project, and composer require vendor/package adds dependencies. The composer.json file defines all requirements and autoload settings.
Beginner 4. How do you define a basic route in Laravel?
// web.php (for web routes with CSRF and session)
Route::get('/hello', function () {
return 'Hello World';
});
// Route with parameter
Route::get('/user/{id}', [UserController::class, 'show']);Beginner 5. What is Blade? Show a simple if‑else example.
Blade is Laravel’s templating engine that compiles to plain PHP. It uses directives like @if, @foreach, @php.
@if($user->isAdmin())
<h1>Admin Panel</h1>
@else
<h2>Welcome, {{ $user->name }}</h2>
@endifBeginner 6. How to create a new Laravel project using Composer?
composer create-project --prefer-dist laravel/laravel my-appBeginner 7. What is Artisan? Give three common commands.
Artisan is Laravel’s command‑line interface. Common commands: php artisan serve (start dev server), php artisan make:model Product, php artisan migrate, php artisan tinker.
Beginner 8. What is Eloquent ORM?
Eloquent is Laravel’s Object‑Relational Mapper (ORM). Each database table has a corresponding model that allows you to query and manipulate data using expressive syntax instead of raw SQL.
Beginner 9. Write a simple Eloquent query to fetch all active users.
$activeUsers = User::where('status', 'active')->get();Beginner 10. How do you pass data from a controller to a view?
// In controller
return view('profile', ['user' => $user]);
// Or using compact()
return view('profile', compact('user'));
// In Blade: {{ $user->name }}Beginner 11. What is a migration? Give an example.
Migration is version control for your database. It defines table structure using PHP code. Example:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});Beginner 12. How do you create a new controller?
php artisan make:controller ProductControllerBeginner 13. What is a CSRF token and how does Laravel protect against CSRF?
Cross‑Site Request Forgery (CSRF) protection is provided by adding a hidden _token field in forms. Laravel automatically checks the token for all POST/PUT/DELETE requests. Use @csrf directive in Blade forms.
Beginner 14. Explain the directory structure of a fresh Laravel project (briefly).
Key folders: app/ (Models, Http/Controllers, Middleware), routes/ (web.php, api.php), resources/views/, database/migrations/, public/ (entry point), config/, .env.
Beginner 15. How do you define environment variables?
In the .env file. Example: DB_DATABASE=my_db. Access via env('DB_DATABASE') or config('database.connections.mysql.database').
Beginner 16. What is the purpose of the public directory?
It is the document root. Contains the index.php front controller, assets (CSS, JS, images). All HTTP requests go through public.
Beginner 17. What is a Laravel collection? Show a simple map.
$collection = collect([1,2,3]);
$multiplied = $collection->map(fn($item) => $item * 2); // [2,4,6]Beginner 18. How do you generate a model with migration and controller?
php artisan make:model Post -mcBeginner 19. What is the difference between get() and first()?
get() returns a Collection of all matching rows. first() returns a single model instance (or null).
Beginner 20. How to create a simple form in Blade?
<form method="POST" action="/submit">
@csrf
<input name="email">
<button type="submit">Send</button>
</form>Beginner 21. What is the dd() helper?
Dump and Die. It prints a variable and stops execution. Useful for debugging.
Beginner 22. How do you enable error details during development?
Set APP_DEBUG=true in the .env file.
Beginner 23. What is the php artisan serve command?
Starts PHP’s built‑in development server (usually at http://localhost:8000).
Beginner 24. How do you define a basic one‑to‑one relationship in Eloquent?
// User model
public function phone() {
return $this->hasOne(Phone::class);
}
// Phone model
public function user() {
return $this->belongsTo(User::class);
}Beginner 25. What is the @yield directive?
Defines a section in a master layout that child views can fill with @section.
// layout.blade.php: <title>@yield('title')</title>
// child: @section('title', 'Home Page')Beginner 26. How to include a sub‑view?
@include('partials.header')
Beginner 27. What does @csrf do?
Inserts a hidden input field with the CSRF token. Required for POST forms.
Beginner 28. How to redirect back with input?
return redirect()->back()->withInput();Beginner 29. What is the redirect() helper?
Creates a redirect response. return redirect('/home');
Beginner 30. How to validate a form request?
$request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users'
]);Beginner 31. What is a named route? How to generate URL?
Route::get('/profile', [ProfileController::class, 'index'])->name('profile');
// Generate: route('profile');Beginner 32. How to check if a view exists?
View::exists('dashboard') returns boolean.Beginner 33. What is a Seeder? How to run?
Seeds database with dummy data. php artisan db:seed or php artisan migrate --seed.
Beginner 34. How to define a fillable property in a model?
protected $fillable = ['name', 'email', 'password'];Beginner 35. What is the @foreach loop in Blade?
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeachBeginner 36. Explain the @unless directive.
Opposite of @if. Runs block if condition is false. @unless($user->active) ... @endunless
Beginner 37. How to get the current authenticated user?
auth()->user() or $request->user().Beginner 38. What are Laravel starter kits?
Laravel Breeze, Jetstream, and Laravel UI provide pre‑built authentication and dashboard scaffolding.
Beginner 39. How to define a simple middleware route group?
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', DashboardController::class);
});Beginner 40. What is @guest and @auth?
Blade directives to check authentication status. @guest if not logged in, @auth if logged in.
Beginner 41. How to set a flash message in session?
return redirect('/')->with('status', 'Profile updated!');
// In Blade: @if(session('status')) ... @endifBeginner 42. What does php artisan route:list do?
Displays all registered routes with methods, URIs, and middleware.
Beginner 43. How to access request input?
$request->input('name') or $request->name (magic method).Beginner 44. What is the .env file?
Stores environment‑specific configuration (database, mail, app key). Not committed to version control.
Beginner 45. How to generate application key?
php artisan key:generate sets APP_KEY in .env.Beginner 46. What is bcrypt() helper?
Hashes a string using Bcrypt. $hashed = bcrypt('secret');
Beginner 47. Explain the __() helper function.
Retrieves a translated string from language files. echo __('messages.welcome');
Beginner 48. How to clear configuration cache?
php artisan config:clearBeginner 49. What is Tinker?
An interactive REPL that allows you to run Eloquent queries and test code from the command line.
Beginner 50. How to define a fallback route?
Route::fallback(function () {
return response()->view('errors.404', [], 404);
});🔵 Intermediate Laravel Questions (60)
Dive deeper into service container, queues, events, and real‑world patterns.
Intermediate 51. Explain Laravel’s service container and dependency injection.
The service container (IoC container) manages class dependencies and performs dependency injection automatically. You can bind interfaces to implementations and resolve them out of the container. Controllers’ constructors and methods can type‑hint dependencies; the container injects them.
Intermediate 52. What are Service Providers? Why are they important?
Service providers are the central place to bootstrap application services: register bindings, event listeners, middleware, routes. Every major Laravel component (Auth, Cache, Queue) has its own provider.
Intermediate 53. How to bind an interface to a concrete class in the container?
// In AppServiceProvider register()
$this->app->bind(PaymentGateway::class, StripeGateway::class);Intermediate 54. Explain the difference between bind() and singleton().
bind() returns a new instance every time it’s resolved. singleton() resolves the same instance throughout the request lifecycle.
Intermediate 55. What are facades? Provide an example.
Facades provide a static interface to classes registered in the service container. E.g., Cache::get('key') resolves the cache service behind the scenes. They are not static methods but proxy to underlying classes.
Intermediate 56. How does Eloquent handle one‑to‑many relationships?
// Post model: return $this->hasMany(Comment::class);
// Comment model: return $this->belongsTo(Post::class);
// Usage: $post->comments;Intermediate 57. What is eager loading, and why use it?
Eager loading solves N+1 problem. Instead of loading relations one by one, use with() to load them in advance. Post::with('comments')->get();
Intermediate 58. Explain query scopes (local and global).
Local scope: prefix method with scope on model, e.g., scopeActive($query). Global scope: implements Scope interface and added in model’s booted().
Intermediate 59. How to create a many‑to‑many relationship with pivot table?
// User model: return $this->belongsToMany(Role::class);
// Role model: return $this->belongsToMany(User::class);
// Pivot table: role_userIntermediate 60. What are polymorphic relationships? Give an example.
Allows a model to belong to multiple other models via a single association. Example: Comment belongs to both Post and Video. Uses commentable_id and commentable_type.
Intermediate 61. How to implement file uploads in Laravel?
$path = $request->file('avatar')->store('avatars', 'public');
// Or using Storage facade: Storage::disk('s3')->put(...);Intermediate 62. Explain Laravel’s queue system.
Queues allow deferring time‑consuming tasks (email sending, PDF generation) to background workers. Drivers: database, Redis, SQS. Dispatch a job with ProcessPodcast::dispatch($podcast);.
Intermediate 63. How to create a job class?
php artisan make:job SendWelcomeEmailIntermediate 64. What is a failed job? How to handle?
If a job exceeds its retry attempts, it’s moved to the failed_jobs table. Use php artisan queue:failed and queue:retry.
Intermediate 65. Explain event and listener system.
Use Event classes and Listener classes. Register in EventServiceProvider. Dispatch: event(new OrderShipped($order));
Intermediate 66. How to schedule tasks (cron jobs) in Laravel?
Define commands in app/Console/Kernel.php schedule() method. Example: $schedule->command('emails:send')->daily();. Add a single cron entry: * * * * * cd /path && php artisan schedule:run
Intermediate 67. What is middleware? How to create a custom one?
Middleware filters HTTP requests. Create with php artisan make:middleware CheckAge. Register in Kernel.php.
Intermediate 68. Explain route model binding.
Automatically inject model instance matching route parameter. In route: Route::get('/post/{post}', ...) – the controller receives a Post object.
Intermediate 69. How to handle API authentication using Laravel Sanctum?
Sanctum provides token‑based authentication for SPAs and mobile apps. Install via composer, publish config, use HasApiTokens trait on User model.
Intermediate 70. What is the difference between api and web middleware groups?
web includes session, CSRF, cookie encryption. api typically stateless, uses token auth (Sanctum/Passport).
Intermediate 71. How to use caching in Laravel? Give an example.
$value = Cache::remember('users', 600, fn() => User::all());Intermediate 72. What are Eloquent accessors and mutators?
Accessors transform attribute when reading. Mutators transform when setting. Defined as getFirstNameAttribute() and setFirstNameAttribute().
Intermediate 73. How to handle multiple database connections?
Define connections in config/database.php. Use DB::connection('mysql2')->table(...) or set $connection on models.
Intermediate 74. Explain the repository pattern in Laravel.
Repository acts as a layer between controllers and models, abstracting data access. Helps in unit testing by mocking repository interfaces.
Intermediate 75. What is Laravel Mix?
Laravel Mix is a wrapper around Webpack to compile and minify CSS/JS assets. It simplifies frontend build process.
Intermediate 76. 🤖 AI Trend How to integrate OpenAI API with Laravel for a chatbot?
Use Http client to POST to OpenAI endpoint. Store conversation in database. Process responses and return via controller. Use queue jobs for long requests.
$response = Http::withToken(env('OPENAI_KEY'))
->post('https://api.openai.com/v1/chat/completions', [...])->json();Intermediate 77. How to send emails in Laravel?
Create a Mailable with php artisan make:mail OrderShipped. Build in build() method, then Mail::to($user)->send(new OrderShipped($order));
Intermediate 78. What are Eloquent resources (API resources)?
Transform models and collections into JSON responses. php artisan make:resource UserResource. Override toArray().
Intermediate 79. How to implement soft deletes?
Add SoftDeletes trait to model and deleted_at column. Then delete() only sets timestamp; records are “trashed”. Retrieve with withTrashed().
Intermediate 80. What is the observer pattern in Laravel?
Observers listen for Eloquent events (created, updated, deleted) on a model. Register in EventServiceProvider or using ObservedBy attribute.
Intermediate 81. Explain database transactions in Laravel.
DB::transaction(function () {
// multiple queries
});Intermediate 82. How to handle file storage using Laravel’s filesystem?
Configure disks in config/filesystems.php. Use Storage::disk('s3')->put('file.jpg', $contents);
Intermediate 83. What are Laravel notifications? Give an example.
Send across channels: mail, database, Slack. php artisan make:notification InvoicePaid. $user->notify(new InvoicePaid($invoice));
Intermediate 84. How to use the @verbatim directive in Blade?
Prevents Blade from parsing JavaScript curly braces. @verbatim ... @endverbatim.
Intermediate 85. What is the difference between factory() and seed()?
Factories define blueprint for creating fake models; seeders use those to insert test data into database.
Intermediate 86. Explain the concept of “helper functions”. Name five.
Global functions like dd(), view(), route(), request(), config().
Intermediate 87. How to create a custom Artisan command?
php artisan make:command SendNewsletter Then define signature and handle method.Intermediate 88. What is the purpose of php artisan down and up?
Maintenance mode. down displays a custom 503 page while you update the app.
Intermediate 89. How to optimize Laravel for production?
Cache config, routes, views: php artisan config:cache, route:cache, view:cache. Use OPcache, queue workers, proper server setup.
Intermediate 90. What is the Throttle middleware?
Limits request rate to prevent abuse. Example: Route::middleware('throttle:60,1')->...
Intermediate 91. Explain the concept of Gates and Policies.
Gates define authorization logic using closures. Policies are classes that group authorization rules for a model.
Intermediate 92. How to handle CORS in Laravel?
Use fruitcake/laravel-cors package (or built‑in middleware in Laravel 11+). Configure allowed origins in config.
Intermediate 93. What is Laravel Sanctum vs Passport?
Sanctum: lightweight token‑based auth for SPAs and simple APIs. Passport: full OAuth2 server implementation.
Intermediate 94. How to create a custom validation rule?
php artisan make:rule Uppercase Implement passes() method.Intermediate 95. Explain the when() method in queries.
User::when($request->role, fn($q, $role) => $q->where('role', $role))->get();Intermediate 96. What is the purpose of php artisan tinker?
Interactive shell for running Eloquent queries and testing small code snippets.
Intermediate 97. How to use DB::raw() for complex expressions?
User::select(DB::raw('count(*) as user_count'))->groupBy('status')->get();Intermediate 98. What are real‑time facades?
Prefix a class with Facades\App\Services\PaymentGateway to use it as a facade without creating a separate facade class.
Intermediate 99. How to implement caching with Redis?
Set CACHE_DRIVER=redis in .env. Use Cache::put('key', 'value', $seconds);
Intermediate 100. Explain the @push and @stack directives.
Push content to a named stack from child views; render stack in layout with @stack('scripts').
Intermediate 101. How to log messages in Laravel?
Log::info('User logged in', ['id' => $user->id]); Configure channels in config/logging.php.Intermediate 102. What is the purpose of php artisan optimize?
Generates optimized class loader, config, and route caches for better performance.
Intermediate 103. How to use @error directive in Blade?
@error('email') <div class="error">{{ $message }}</div> @enderrorIntermediate 104. What is the difference between Session::put and Session::flash?
put persists until manually removed. flash keeps data only for the next request.
Intermediate 105. How to implement a repository with interface binding?
$this->app->bind(UserRepositoryInterface::class, EloquentUserRepository::class);Intermediate 106. Explain the pluck() method on collections.
$emails = User::all()->pluck('email');Intermediate 107. What are chunk() and lazy() for large datasets?
chunk processes records in batches to reduce memory. lazy returns a LazyCollection for memory‑efficient iteration.
Intermediate 108. How to use cache()->rememberForever()?
$value = Cache::rememberForever('key', fn() => expensiveQuery());Intermediate 109. What is the HTTP client in Laravel? Show a GET request.
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.example.com/users');Intermediate 110. How to create a custom middleware that logs request duration?
public function handle($request, $next) {
$start = microtime(true);
$response = $next($request);
$duration = microtime(true) - $start;
Log::info('Request took ' . $duration . ' sec');
return $response;
}🟣 Expert Laravel Questions (50)
Expert 111. How does the service container resolve dependencies under the hood?
The container uses reflection to inspect type‑hinted parameters and recursively resolves them. It first checks for any explicit binding, then attempts to build the class automatically.
Expert 112. Explain deferred service providers.
Providers that only load when their service is actually needed. Set protected $defer = true and implement provides().
Expert 113. How to implement custom caching driver?
Extend Illuminate\Cache\Repository, implement store interface, and register via Cache::extend() in a provider.
Expert 114. What are Eloquent higher order messages?
E.g., $users->each->markAsVerified() – applies the method to each collection member without a closure.
Expert 115. How to create a custom Eloquent cast?
Implement CastsAttributes interface, then use $casts array with the custom cast class name.
Expert 116. Discuss database connection resolution and the “connect” event.
When first query runs, connection is resolved from config. You can listen to Illuminate\Database\Events\ConnectionEstablished.
Expert 117. 🤖 AI How would you build an AI recommendation engine using Laravel and vector embeddings?
Store embeddings in a dedicated column (e.g., using pgvector or a separate vector DB). Use AI service (OpenAI embeddings) to convert product descriptions. Query with cosine similarity via raw SQL or Eloquent scope. Combine with caching for performance.
Expert 118. Explain the concept of “contextual binding”.
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(fn() => Storage::disk('local'));Expert 119. How to use ResponseFactory macros?
Response::macro('caps', fn($value) => response(strtoupper($value)));Expert 120. Explain Laravel’s pipeline implementation.
Pipelines send a passable through a series of pipes (middleware). Used in HTTP middleware, job pipeline. Each pipe can modify and pass along.
🔴 Most Expert / Architect Level (40)
Architect 161. How to design a modular monolith with Laravel?
Use folders per module (e.g., App/Modules/Invoicing) with own routes, controllers, models. Register module service providers dynamically. Maintain strict boundaries.
Architect 162. Implementing CQRS with Laravel.
Separate read and write models. Use Eloquent for writes, optimized raw queries/views for reads. Jobs and events handle synchronization.
Architect 163. How to handle eventual consistency in a Laravel microservices setup?
Use message queues (Redis/RabbitMQ) and event sourcing. Laravel can dispatch events to external services via jobs and HTTP.
Architect 164. Design a rate limiter with dynamic rules using Redis.
Redis::throttle('key')->allow(10)->every(60)->then(...)Architect 165. 🤖 AI Building a full‑fledged AI chat support system with Laravel Reverb and OpenAI streaming.
Use Laravel Reverb for real‑time WebSocket, stream AI responses via Server‑Sent Events or chunked jobs. Combine event broadcasting and queue.
💼 Business Problem Scenarios (15 Cases)
lockForUpdate()), or queue inventory decrements.Config::set() dynamically.🧪 Hands‑on Labs (10 Interactive Exercises)
Lab 1: Build a Task API with authentication (Sanctum).
Step 1: Install Sanctum, publish config. Step 2: Create Task model, migration, controller. Step 3: Protect routes with auth:sanctum. Step 4: Test with Postman.
Lab 2: Implement real‑time notifications using Laravel Echo and Reverb.
Set up Reverb server, create event MessageSent, broadcast it, listen on frontend with Echo.
Lab 3: Create a custom Artisan command to generate monthly report and email it.
Generate command, query orders from last month, create PDF using DomPDF, dispatch email via Mailable.
Lab 4: Build a file upload with chunked resumable uploads.
Use a package like pion/laravel-chunk-upload or build custom with JavaScript splitting, reassemble on server.
Lab 5: Implement a repository pattern with unit tests.
Create interface, Eloquent repository, bind in service provider, write PHPUnit tests mocking repository.
Lab 6: Integrate Stripe payment with webhook handling.
Use stripe/stripe-php, create checkout controller, handle payment_intent.succeeded webhook.
Lab 7: 🤖 AI Build a simple AI image generator using OpenAI DALL‑E API.
Create form, send prompt via HTTP client, save returned image URL or file, display to user.
Lab 8: Optimize a slow query with eager loading and indexing.
Identify N+1 using Laravel Debugbar, refactor with with(), add database indexes.
Lab 9: Set up continuous integration for a Laravel app with GitHub Actions.
Create .github/workflows/laravel.yml, run tests, lint, build assets.
Lab 10: Implement a custom validation rule that checks if a coupon is valid.
Create CouponRule, inject database, check expiry and usage limit.
📝 Code‑Based Challenges (12 Exercises)
Challenge 1: Refactor a controller that has 500 lines into single‑action controllers and services.
Split each action into __invoke controller; extract business logic into service classes.
Challenge 2: Write a query to get top 5 customers by total order value in last month.
Customer::select('customers.*')
->join('orders', 'customers.id', '=', 'orders.customer_id')
->where('orders.created_at', '>=', now()->subMonth())
->groupBy('customers.id')
->orderByRaw('SUM(orders.total) desc')
->limit(5)
->get();Challenge 3: Implement a custom Laravel collection macro “toUpper” for strings.
Collection::macro('toUpper', function () {
return $this->map(fn($item) => strtoupper($item));
});Challenge 4: Create a middleware that checks if user is an admin or returns 403.
public function handle($request, $next) {
if (! $request->user()?->isAdmin()) {
abort(403);
}
return $next($request);
}Challenge 5: Write a test that ensures a job is dispatched when user registers.
Event::fake();
// ... perform registration
Event::assertDispatched(Registered::class);Challenge 6: Build a custom Eloquent relationship (e.g., “most recent comment”).
public function latestComment() {
return $this->hasOne(Comment::class)->latestOfMany();
}Challenge 7: 🤖 AI Generate a personalized product description using AI based on user preferences stored in DB.
$prompt = "Write a product description for {$product->name} targeting user who likes {$user->preferences}";
$desc = Http::withToken(env('OPENAI_KEY'))->post('...', ['prompt' => $prompt])->json()['choices'][0]['text'];Challenge 8: Implement a dynamic where clause that builds query based on request filters.
$query = Product::query();
if ($request->category) { $query->where('category_id', $request->category); }
if ($request->min_price) { $query->where('price', '>=', $request->min_price); }
return $query->paginate();Challenge 9: Create a custom validation rule that enforces password complexity.
public function passes($attribute, $value) {
return preg_match('/[A-Z]/', $value) && preg_match('/[0-9]/', $value);
}Challenge 10: Write a job that processes a CSV import with progress tracking.
Use Bus::batch and chunk CSV, update a import_progress table.
Challenge 11: Implement API rate limiting using Laravel’s built‑in throttle and a custom Redis limiter for VIP users.
RateLimiter::for('api', fn($job) => $job->user()->isVip() ? Limit::none() : Limit::perMinute(60));Challenge 12: Create a Blade component that renders a dynamic chart using a library (Chart.js).
// chart.blade.php component
<canvas id="myChart"></canvas>
@push('scripts')
<script>new Chart(...)</script>
@endpush

No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam