Technology

Laravel Interview Questions and Answers

Laravel is the most popular PHP framework. These Laravel interview questions cover routing, controllers, Blade and migrations for freshers, then Eloquent relationships, middleware, the service container, queues, events, authentication, testing and performance for experienced Laravel developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise Laravel questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Laravel Interview Questions with answers. Examples: What is Laravel, and why is it popular? What are migrations and seeders? What is Blade? What are Eloquent relationships?
Laravel Interview Questions: 30 questions with model answers on this page.

Basic Laravel interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is Laravel, and why is it popular?

Laravel is a PHP framework that follows the MVC pattern and provides elegant syntax and many built-in features: routing, Eloquent ORM, Blade templates, migrations, authentication, queues, caching, mail and testing. Its documentation, ecosystem (Forge, Vapor, Horizon, Livewire) and developer experience make it the most popular PHP framework.

2. What are migrations and seeders?

Answer flow · 3 steps
  1. Migrations are version control for the database schema: PHP classes that create or change tables, run with php artisan migrate and reversed with rollback.

  2. Seeders insert initial or test data, and factories generate fake model data for testing and seeding.

  3. Together they let every developer and environment build the same database.

3. What is Blade?

Blade is Laravel's templating engine. {{ $value }} prints escaped output to prevent XSS, directives such as @if, @foreach and @auth handle logic, and layouts use @extends, @section and @yield, or components with slots. Templates are compiled to plain PHP and cached for speed.

4. What is Artisan?

Answer flow · 3 steps
  1. Artisan is Laravel's command-line tool.

  2. Common commands are php artisan serve, make:model -mcr (model with migration, controller and resource routes), make:controller, make:request, migrate, db:seed, route:list, tinker (an interactive shell), queue:work, schedule:run and optimize.

  3. You can write custom commands for your own tasks.

5. How does routing work in Laravel?

Routes are defined in routes/web.php and routes/api.php with Route::get, post, put, patch and delete, pointing to closures or controller methods. Route parameters such as {id}, named routes (->name("orders.show")) used with route(), route groups with shared middleware and prefixes, resource routes for CRUD, and route model binding, which loads the model automatically, are the key features.

6. What are resource controllers?

Answer flow · 3 steps
  1. A resource controller has standard methods for CRUD operations: index, create, store, show, edit, update and destroy.

  2. Route::resource("photos", PhotoController::class) registers all the routes in one line, and Route::apiResource excludes the create and edit form routes for APIs.

  3. This keeps controllers consistent.

7. How does validation work in Laravel?

Answer flow · 3 steps
  1. Call $request->validate([...]) with rules such as required, email, unique:users,email, min, max, confirmed and exists, or move them into a Form Request class with rules() and authorize().

  2. Invalid input redirects back with errors for web requests, or returns a 422 JSON response for APIs.

  3. Custom rules can be written as classes or closures.

8. How do configuration and the .env file work?

Answer flow · 3 steps
  1. Environment-specific values such as database credentials and API keys live in .env, which is never committed.

  2. Config files in the config folder read them with env(), and the app reads config with config("services.stripe.key").

  3. Calling env() outside config files breaks when config is cached with php artisan config:cache.

9. How do you create and query records with Eloquent?

Answer flow · 3 steps
  1. Each table has a model class.

  2. Post::create($data) inserts (with $fillable set for mass assignment), Post::find($id) or findOrFail fetches by key, Post::where("status", "published")->latest()->paginate(10) queries, $post->update($data) updates and $post->delete() deletes.

  3. Results are collections with helpful methods such as map, filter and pluck.

10. How does Laravel protect against CSRF?

Answer flow · 3 steps
  1. Laravel generates a CSRF token for each session and the VerifyCsrfToken middleware checks it on POST, PUT, PATCH and DELETE requests from web routes.

  2. Forms include it with the @csrf Blade directive, and JavaScript requests send it in the X-CSRF-TOKEN header.

  3. API routes using tokens are stateless and do not need CSRF tokens.

11. What is mass assignment protection?

Answer flow · 4 steps
  1. Mass assignment means filling a model from an array, such as User::create($request->all()).

  2. If any field were allowed, an attacker could set fields such as is_admin.

  3. Laravel protects against this with $fillable (an allow-list of fields) or $guarded (a block-list).

  4. Using $request->validated() to pass only validated data is the safest practice.

Intermediate Laravel interview questions

Applied problems, trade-offs and questions about your own projects.

12. What are Eloquent relationships?

Eloquent defines relationships as methods on models: hasOne and belongsTo for one-to-one, hasMany and belongsTo for one-to-many, belongsToMany for many-to-many with a pivot table, hasManyThrough for distant relations, and polymorphic relationships such as morphMany for comments on several models. They are queried as properties, such as $post->comments.

13. What is eager loading, and why does it matter?

Answer flow · 3 steps
  1. By default relationships load lazily, so looping over 50 posts and reading $post->author runs 51 queries, the N+1 problem.

  2. Eager loading with Post::with('author')->get() loads all authors in one extra query.

  3. Laravel can throw an exception on lazy loading in development with Model::preventLazyLoading() to catch these problems early.

14. What is middleware in Laravel?

Answer flow · 3 steps
  1. Middleware filters HTTP requests entering the app, such as auth to check the user is logged in, throttle for rate limiting, and verified for email verification.

  2. Custom middleware is created with artisan and can run before or after the request.

  3. It is attached to routes or groups, or registered globally in bootstrap/app.php in Laravel 11 and later.

15. What are queues in Laravel?

Answer flow · 3 steps
  1. Queues move slow tasks, such as sending emails, processing images or calling external APIs, into background jobs so the user gets a fast response.

  2. A job class is dispatched with dispatch(), stored in a queue driver such as Redis, database or SQS, and processed by php artisan queue:work.

  3. Horizon monitors Redis queues, and failed jobs can be retried.

16. What are casts, accessors and mutators?

Casts convert attributes automatically when reading and writing, such as "is_active" => "boolean", "settings" => "array" or "price" => MoneyCast::class, and "datetime" for Carbon dates. Accessors and mutators, defined with Attribute::make(get: ..., set: ...), transform values, for example formatting a full name or hashing a password when it is set.

17. What are query scopes?

Answer flow · 3 steps
  1. Local scopes are reusable query constraints defined on the model, such as scopePublished, used as Post::published()->get().

  2. Global scopes apply automatically to every query on a model, such as filtering by the current tenant, and SoftDeletes uses a global scope to hide deleted rows.

  3. Scopes keep query logic in one place.

18. How do events and listeners work in Laravel?

Answer flow · 3 steps
  1. An event class represents something that happened, such as OrderPlaced, and listeners respond to it, such as sending a confirmation email or updating stock.

  2. Events are dispatched with OrderPlaced::dispatch($order), and listeners can implement ShouldQueue to run in the background.

  3. Model observers react to Eloquent events such as created and updated.

19. How do mail and notifications work in Laravel?

Answer flow · 3 steps
  1. Mailables are classes that build emails with Blade or Markdown templates and are sent with Mail::to($user)->send(new OrderShipped($order)), usually queued.

  2. Notifications send the same message over several channels, such as mail, database, SMS through Vonage, Slack or broadcast, from one class with a via() method.

  3. Both can be previewed and faked in tests.

20. Which authentication options does Laravel offer?

Answer flow · 3 steps
  1. Starter kits (React, Vue or Livewire) provide login, registration, password reset and email verification out of the box; Breeze and Jetstream are the older kits.

  2. Fortify is a backend-only authentication implementation.

  3. Sanctum handles API tokens and SPA cookie authentication, Passport provides a full OAuth2 server, and Socialite adds login with Google, GitHub and others.

21. What are facades?

Answer flow · 3 steps
  1. Facades provide a static-looking interface, such as Cache::get() or DB::table(), to services in the container.

  2. Behind the scenes, Laravel resolves the real object from the container and calls the method on it, so facades are still testable with Cache::shouldReceive() or fakes such as Mail::fake().

  3. Dependency injection is an equally valid alternative.

22. How do you store files in Laravel?

The Storage facade gives one API for the local disk, S3 and other cloud storage, configured in config/filesystems.php. $request->file("avatar")->store("avatars", "s3") saves an upload with a unique name, Storage::url() builds public URLs, temporaryUrl() creates expiring links for private files, and php artisan storage:link exposes the public disk.

High level Laravel interview questions

System design, deep internals, leadership and tough follow-ups.

23. What is the service container, and what are service providers?

Answer flow · 3 steps
  1. The service container manages class dependencies and performs dependency injection, resolving classes automatically through type hints in constructors and methods.

  2. You can bind interfaces to implementations, or register singletons.

  3. Service providers are where bindings, event listeners, routes and other bootstrapping are registered; their register method binds and their boot method runs after all providers are registered.

24. How do you build a secure API with Laravel?

Answer flow · 3 steps
  1. I define routes in routes/api.php, use API resources to shape JSON responses, validate input with Form Request classes, and authorise actions with policies and gates.

  2. Authentication uses Sanctum for SPA and mobile tokens, or Passport for full OAuth2.

  3. I apply rate limiting, use mass-assignment protection with $fillable, and version the API.

25. How do you optimise a Laravel application for production?

Run php artisan optimize to cache config, routes, events and views, use composer install --optimize-autoloader --no-dev, enable OPcache, and use Redis for cache, sessions and queues. Eager load relationships, add database indexes, cache heavy queries, paginate, move slow work to queues, and consider Laravel Octane to keep the app in memory between requests.

26. Explain the Laravel request lifecycle.

Answer flow · 3 steps
  1. Every request enters public/index.php, which loads Composer's autoloader and creates the application from bootstrap/app.php.

  2. The HTTP kernel runs global middleware, service providers register and boot services, the router matches the route, runs route middleware and calls the controller, and the response travels back through the middleware to the browser.

  3. Terminable middleware can run after the response is sent.

27. How do you test a Laravel application?

Answer flow · 4 steps
  1. Laravel supports PHPUnit and Pest.

  2. Feature tests send HTTP requests with $this->get() and $this->postJson() and make assertions on status, JSON and the database, using RefreshDatabase and model factories for data.

  3. Fakes for Mail, Queue, Event, Notification, Storage and Http let you test side effects without sending anything.

  4. Browser tests use Dusk.

28. What are Laravel Octane and Horizon?

Octane keeps the application in memory between requests using FrankenPHP, Swoole or RoadRunner, removing the start-up cost of every request and greatly increasing throughput, but code must avoid leaking state between requests. Horizon is a dashboard and configuration system for Redis queues, showing throughput, failed jobs and worker balancing.

29. What are Livewire and Inertia?

Livewire builds dynamic interfaces with PHP classes and Blade templates; the frontend communicates with the server through AJAX automatically, so you can build reactive pages without writing much JavaScript. Inertia connects Laravel to React, Vue or Svelte pages without building a separate API: controllers return Inertia responses and the frontend renders them as a single-page app.

30. How do you deploy and scale a Laravel application?

Answer flow · 3 steps
  1. Deploy with tools such as Laravel Cloud, Forge, Vapor (serverless on AWS) or Envoyer for zero-downtime releases, or with containers.

  2. Run php artisan optimize, migrations and queue restarts on each release.

  3. Scale with several app servers behind a load balancer, shared Redis for cache, sessions and queues, separate queue workers supervised by Horizon, the scheduler running on one server, and files on S3.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a backend developer interview?

See all Backend Developer interview questions, covering Node.js, Express.js, NestJS, Python, Django and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields