Top 50 Laravel Interview Questions and Answers

Commonly asked Laravel interview questions, from fundamentals to advanced concepts.

1.What is Laravel?

Laravel is a free, open-source PHP web application framework known for its elegant syntax and developer-friendly tools.

  • Follows the MVC (Model-View-Controller) architectural pattern.
  • Provides built-in solutions for routing, authentication, ORM (Eloquent), templating (Blade), and more — reducing boilerplate for common web app needs.

2.What is the MVC architecture, and how does Laravel implement it?

MVC separates an application into three interconnected components:

  • Model: represents data and business logic (Laravel's Eloquent models).
  • View: the presentation layer shown to the user (Laravel's Blade templates).
  • Controller: handles requests, coordinates between Model and View, and returns a response.
  • This separation improves maintainability by keeping data, logic, and presentation concerns independent.

3.What is Eloquent ORM in Laravel?

Eloquent is Laravel's built-in Object-Relational Mapper (ORM), letting you interact with database tables using PHP objects instead of raw SQL.

$users = User::where('active', true)->get();
  • Each Eloquent model corresponds to a database table, following "convention over configuration" (e.g., a User model maps to the users table).

4.What is the difference between Eloquent and Query Builder in Laravel?

Both interact with the database, at different levels of abstraction:

  • Eloquent: an ORM working with model objects, providing relationships, mutators, and events — more expressive for object-oriented code.
  • Query Builder: a lower-level, fluent interface for building SQL queries directly without needing a defined model — slightly faster and more flexible for complex raw queries.
DB::table('users')->where('active', true)->get();

5.What are Migrations in Laravel?

Migrations are version-controlled PHP files that define changes to the database schema.

Schema::create('users', function (Blueprint $table) {
  $table->id();
  $table->string('name');
  $table->timestamps();
});
  • Run with php artisan migrate, allowing teams to keep database schemas in sync across environments without manual SQL scripts.

6.What are Seeders in Laravel?

Seeders populate the database with sample or default data, typically for development/testing.

php artisan make:seeder UserSeeder
php artisan db:seed
  • Often paired with Factories to generate realistic fake data using libraries like Faker.

7.What is Blade in Laravel?

Blade is Laravel's lightweight templating engine for building views.

@if ($user->isAdmin())
  <p>Welcome, Admin {{ $user->name }}</p>
@endif
  • Compiles templates into plain PHP for performance, and supports layouts, components, and template inheritance via @extends/@section.

8.What are Routes in Laravel, and how are they defined?

Routes map incoming URLs to controller actions or closures.

Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
  • Defined in routes/web.php (browser-facing) or routes/api.php (stateless API endpoints).

9.What is Middleware in Laravel?

Middleware filters HTTP requests entering the application, running before (or after) a request reaches its route handler.

public function handle($request, Closure $next) {
  if (!$request->user()) {
    return redirect('login');
  }
  return $next($request);
}
  • Common uses: authentication checks, logging, CORS handling, and request throttling.

10.What is the difference between Route Middleware and Global Middleware in Laravel?

Both run during the request lifecycle, but with different scope:

  • Global Middleware: runs on every HTTP request to the application.
  • Route Middleware: applied selectively to specific routes or route groups (e.g., auth, throttle).

11.What are Controllers in Laravel?

Controllers group related request-handling logic into a single class, instead of defining everything as closures in route files.

class UserController extends Controller {
  public function index() {
    return User::all();
  }
}
  • Created via php artisan make:controller UserController.

12.What are Resource Controllers in Laravel?

A Resource Controller automatically generates all the standard CRUD methods (index, create, store, show, edit, update, destroy) for a resource.

Route::resource('users', UserController::class);
  • One line registers all seven conventional RESTful routes for that controller.

13.What is Dependency Injection in Laravel?

Laravel's Service Container automatically resolves and injects class dependencies, typically via constructor or method type-hinting.

public function __construct(private UserRepository $users) {}
  • Laravel inspects the type-hint and automatically provides an instance, simplifying testing (dependencies can be swapped/mocked) and decoupling classes.

14.What is the Service Container in Laravel?

The Service Container is Laravel's tool for managing class dependencies and performing dependency injection.

  • Automatically resolves most classes without explicit configuration.
  • For interfaces or complex bindings, you register them explicitly:
$this->app->bind(PaymentGateway::class, StripeGateway::class);

15.What are Service Providers in Laravel?

Service Providers are the central place where Laravel applications bootstrap services — binding classes into the container, registering event listeners, or configuring packages.

class AppServiceProvider extends ServiceProvider {
  public function register() {
    $this->app->bind(PaymentGateway::class, StripeGateway::class);
  }
}
  • Every Laravel application/package registers its services through one or more providers, listed in config/app.php.

16.What are Facades in Laravel?

Facades provide a static-like interface to classes registered in the service container.

Cache::put('key', 'value', 60);
Route::get('/home', ...);
  • Under the hood, they resolve the underlying object from the container dynamically — offering concise syntax while still being tested/mockable.

17.What is the difference between Facades and Dependency Injection in Laravel?

Both access the same underlying services, but with different styles:

  • Facades: concise, static-style calls, resolved dynamically from the container — convenient but can obscure a class's real dependencies.
  • Dependency Injection: dependencies are explicitly declared (usually via constructor), making them clearer and slightly easier to unit test in isolation.

18.What is Artisan in Laravel?

Artisan is Laravel's built-in command-line interface (CLI) tool.

php artisan make:model Product -m
php artisan migrate
php artisan tinker
  • Provides commands for generating boilerplate (models, controllers, migrations), running migrations, clearing caches, and more.

19.What is Tinker in Laravel?

Tinker is an interactive REPL (via Artisan) for experimenting with a Laravel application's code directly.

php artisan tinker
>>> User::find(1)->email;
  • Useful for quickly testing Eloquent queries or debugging application logic without writing a full script.

20.What are Route Model Bindings in Laravel?

Route Model Binding automatically injects the matching Eloquent model instance into a route/controller, based on a URL segment.

Route::get('/users/{user}', function (User $user) {
  return $user->email;
});
  • Laravel automatically resolves {user} to the corresponding User model (by primary key), throwing a 404 if not found — removing manual find() calls.

21.What is the difference between hasOne, hasMany, belongsTo, and belongsToMany relationships in Eloquent?

These define Eloquent model relationships:

  • hasOne: one-to-one (e.g., a User has one Profile).
  • hasMany: one-to-many (e.g., a User has many Posts).
  • belongsTo: the inverse of hasOne/hasMany (e.g., a Post belongsTo a User).
  • belongsToMany: many-to-many, typically via a pivot table (e.g., Users and Roles).

22.What is Eager Loading in Laravel, and why is it used?

Eager Loading loads a model's relationships upfront in a single additional query, instead of triggering a separate query per record when accessed.

$users = User::with('posts')->get(); // avoids N+1 queries
  • Directly solves the N+1 query problem, significantly improving performance when displaying related data for many records.

23.What is the N+1 query problem, and how does Laravel help solve it?

The N+1 problem occurs when fetching N records triggers N additional queries to fetch each one's related data separately.

// N+1 problem
$users = User::all();
foreach ($users as $user) { echo $user->posts; } // 1 query per user

// solved with eager loading
$users = User::with('posts')->get(); // 2 queries total

24.What are Laravel Form Requests?

Form Requests are dedicated classes that encapsulate validation logic and authorization for a specific request, keeping controllers clean.

class StoreUserRequest extends FormRequest {
  public function rules() {
    return ['email' => 'required|email|unique:users'];
  }
}

public function store(StoreUserRequest $request) { ... }

25.How does Laravel handle validation?

Laravel provides a fluent validation system, usable directly in a controller or via a Form Request class.

$validated = $request->validate([
  'email' => 'required|email',
  'age' => 'required|integer|min:18',
]);
  • If validation fails, Laravel automatically redirects back with error messages (for web routes) or returns a 422 JSON response (for API routes).

26.What are Laravel Events and Listeners?

Events and Listeners implement the observer pattern, decoupling actions from their side effects.

event(new OrderShipped($order));

class SendShipmentNotification {
  public function handle(OrderShipped $event) {
    // send email
  }
}
  • Useful for triggering multiple independent actions (email, logging, notifications) in response to a single event without coupling them together.

27.What are Laravel Jobs and Queues?

Jobs represent units of work that can be executed synchronously or dispatched to run asynchronously via a Queue.

ProcessPodcast::dispatch($podcast);
  • Queues (backed by Redis, database, or SQS) let time-consuming tasks (sending emails, processing files) run in the background without blocking the HTTP response.

28.What is the difference between synchronous and queued job dispatching in Laravel?

Both run the same job class, but differently:

  • Synchronous: the job runs immediately, within the current request, blocking until it finishes (dispatchSync()).
  • Queued: the job is pushed onto a queue and processed later by a separate queue worker process, keeping the HTTP response fast.

29.What is Laravel Sanctum?

Sanctum provides a lightweight authentication system for SPAs, mobile apps, and simple token-based APIs.

  • Issues API tokens tied to a user, without the complexity of full OAuth2.
  • Also supports cookie-based authentication for first-party SPAs sharing the same domain as the backend.

30.What is the difference between Sanctum and Passport in Laravel?

Both handle API authentication, at different complexity levels:

  • Sanctum: simple token-based authentication, ideal for SPAs and mobile apps with a single first-party frontend.
  • Passport: a full OAuth2 server implementation, suited for scenarios needing third-party application access, scopes, and more complex authorization flows.

31.What are Laravel Policies?

Policies organize authorization logic for a specific model, determining what actions a user is allowed to perform.

class PostPolicy {
  public function update(User $user, Post $post) {
    return $user->id === $post->user_id;
  }
}

$this->authorize('update', $post);

32.What is the difference between Gates and Policies in Laravel?

Both handle authorization, but at different scopes:

  • Gates: simple, closure-based authorization checks, good for actions not tied to a specific model (e.g., "can access admin panel").
  • Policies: organized classes tied to a specific model, grouping all authorization logic for that model's actions together.

33.What are Laravel Accessors and Mutators?

They customize how attributes are retrieved or set on an Eloquent model.

protected function name(): Attribute {
  return Attribute::make(
    get: fn ($value) => ucfirst($value),
    set: fn ($value) => strtolower($value),
  );
}
  • Accessor: transforms a value when it's read.
  • Mutator: transforms a value when it's set (e.g., before saving to the database).

34.What are Laravel Scopes (Local and Global)?

Scopes encapsulate reusable query constraints on an Eloquent model.

public function scopeActive($query) {
  return $query->where('active', true);
}
// usage: User::active()->get();
  • Local scopes: applied explicitly by calling them, like the example above.
  • Global scopes: automatically applied to every query for that model, unless explicitly removed.

35.What is CSRF protection in Laravel, and how does it work?

CSRF (Cross-Site Request Forgery) protection prevents malicious sites from submitting unauthorized requests on behalf of an authenticated user.

<form method="POST">
  @csrf
</form>
  • Laravel generates a unique token per session, embedded via @csrf, and automatically validates it on incoming POST/PUT/DELETE requests via the VerifyCsrfToken middleware.

36.What is the purpose of the .env file in Laravel?

The .env file stores environment-specific configuration (database credentials, API keys, app settings) outside of version control.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
APP_KEY=base64:...
  • Values are accessed via env('DB_HOST') (usually wrapped by a config() call), keeping sensitive credentials out of the codebase.

37.What is the difference between config() and env() functions in Laravel?

Both retrieve configuration values, but differ in best practice:

  • env(): reads directly from the .env file — should only be called inside config/*.php files.
  • config(): reads from the cached configuration array (populated from config/*.php files) — should be used everywhere else in application code, especially since env() calls outside config files break when configuration is cached in production.

38.What is Laravel's Query Scopes vs Eloquent Relationships — when would you use each?

They solve different problems:

  • Query Scopes: reusable filtering conditions on a single model (e.g., active(), recent()).
  • Relationships: define how models are connected to other models (e.g., hasMany, belongsTo), enabling eager loading and related queries.
  • Both can be combined, e.g., $user->posts()->published()->get().

39.What are Laravel Collections?

Collections wrap arrays (often Eloquent query results) with a fluent, chainable API for common data manipulation.

$names = User::all()->pluck('name')->filter()->sort()->values();
  • Provides methods like map(), filter(), reduce(), groupBy() — far more expressive than plain PHP array functions.

40.What is the difference between get() and first() in Eloquent?

Both retrieve query results, but differ in what's returned:

  • get(): returns a Collection of all matching records.
  • first(): returns only the first matching record (a single model instance), or null if none found.

41.What is Soft Deleting in Laravel?

Soft Deleting marks a record as deleted (setting a deleted_at timestamp) instead of actually removing it from the database.

use SoftDeletes;
$user->delete(); // sets deleted_at, doesn't remove the row
User::withTrashed()->get(); // includes soft-deleted rows
  • Allows data recovery and auditing, while normal queries automatically exclude soft-deleted records.

42.What is Laravel's Task Scheduling feature?

Laravel's Scheduler lets you define recurring tasks (cron jobs) directly in code, instead of managing individual crontab entries.

$schedule->command('emails:send')->daily();
  • Requires just one actual cron entry on the server (running every minute) to trigger Laravel's own internal scheduler, which then handles the defined schedule.

43.What is the purpose of Laravel's Cache facade?

The Cache facade provides a unified API for storing and retrieving cached data, regardless of the underlying driver (Redis, Memcached, file, database).

$value = Cache::remember('users_count', 3600, function () {
  return User::count();
});
  • remember() caches the result of a closure for a given duration, avoiding expensive recomputation on every request.

44.What is the difference between web.php and api.php route files in Laravel?

Both define routes, but with different default behavior:

  • web.php: routes include session state, CSRF protection, and cookie-based authentication — used for browser-facing pages.
  • api.php: routes are stateless by default (no sessions/CSRF), prefixed with /api, and typically use token-based authentication — designed for REST APIs.

45.What are API Resources in Laravel?

API Resources transform Eloquent models (or collections) into a controlled JSON structure for API responses.

class UserResource extends JsonResource {
  public function toArray($request) {
    return ['id' => $this->id, 'name' => $this->name];
  }
}
  • Prevents accidentally exposing internal model fields, and standardizes API response shapes.

46.What is the purpose of Laravel's Pint tool?

Laravel Pint is an opinionated PHP code style fixer, built on top of PHP-CS-Fixer, preconfigured with Laravel's coding standards.

./vendor/bin/pint
  • Automatically formats code to a consistent style with zero configuration required, though it can be customized via a pint.json file.

47.What testing tools does Laravel provide out of the box?

Laravel ships with PHPUnit integration and helpful testing utilities:

public function test_user_can_register() {
  $response = $this->post('/register', [...]);
  $response->assertStatus(302);
  $this->assertDatabaseHas('users', ['email' => 'a@x.com']);
}
  • Provides HTTP test helpers, database assertions, and factories for generating test data easily.

48.What are Laravel Factories used for in testing?

Factories generate fake model instances with realistic data, commonly using the Faker library.

User::factory()->count(10)->create();
  • Essential for seeding databases and setting up test data quickly, without manually specifying every field.

49.What is the difference between RefreshDatabase and DatabaseTransactions traits in Laravel testing?

Both keep the test database clean between tests, but differently:

  • RefreshDatabase: migrates the database fresh (or uses an in-memory SQLite) for the test suite, resetting the schema as needed.
  • DatabaseTransactions: wraps each test in a database transaction that's rolled back at the end, avoiding actual data persistence — faster since no migration re-run is needed.

50.What is Laravel Octane?

Laravel Octane boosts application performance by keeping the app in memory using high-performance application servers like Swoole or RoadRunner, instead of bootstrapping Laravel from scratch on every request.

  • Dramatically reduces per-request overhead, useful for high-throughput applications.
  • Requires care with global/static state, since the application persists in memory across requests (unlike traditional PHP-FPM's fresh-request model).