Laravel Interview Master
The ultimate collection of 200+ meticulously curated Laravel questions to help you ace your backend developer interview.
What is Laravel?
BeginnerLaravel is a free, open-source PHP web framework created by Taylor Otwell. It follows the model–view–controller (MVC) architectural pattern and is designed for ...
Comprehensive Answer
What are the core features of Laravel?
BeginnerCore features include a modular packaging system with dependency management, different ways for accessing relational databases (Eloquent ORM), utilities that ai...
Comprehensive Answer
What is Artisan in Laravel?
BeginnerArtisan is the name of the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application...
Comprehensive Answer
What is Composer and why does Laravel use it?
BeginnerComposer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for...
Comprehensive Answer
What are Routing basics in Laravel?
BeginnerRouting maps HTTP requests to specific controller actions or closures. Basic Laravel routes accept a URI and a closure, providing a very simple and expressive m...
Comprehensive Answer
PHP/Laravel Example
Route::get('/hello', function () {
return 'Hello World';
});What are CSRF Tokens in Laravel?
BeginnerCSRF stands for Cross-Site Request Forgery. Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token i...
Comprehensive Answer
What is a Controller in Laravel?
BeginnerControllers can group related request handling logic into a single class. For example, a `UserController` might handle all incoming requests related to users, i...
Comprehensive Answer
What are Models in Laravel?
BeginnerModels in Laravel typically reside in the `app/Models` directory. The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementatio...
Comprehensive Answer
What is a Migration?
BeginnerMigrations are like version control for your database, allowing your team to define and share the application's database schema definition. They are paired with...
Comprehensive Answer
What are Views in Laravel?
BeginnerViews separate your application logic from your presentation logic. In Laravel, views are typically defined using the Blade templating engine and are stored in ...
Comprehensive Answer
What is Blade Templating Engine?
BeginnerBlade is the simple, yet powerful templating engine provided with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP ...
Comprehensive Answer
How do you create a controller using Artisan?
BeginnerYou can create a controller using the `make:controller` Artisan command.
Comprehensive Answer
PHP/Laravel Example
php artisan make:controller UserControllerHow do you create a model using Artisan?
BeginnerYou use the `make:model` command. You can also generate a migration simultaneously by appending `-m`.
Comprehensive Answer
PHP/Laravel Example
php artisan make:model Post -mWhat is the file structure of a fresh Laravel project?
BeginnerImportant directories include `app/` (core code, controllers, models), `config/` (configuration files), `database/` (migrations, seeders), `public/` (index.php,...
Comprehensive Answer
What is Database Seeding?
BeginnerLaravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the `database/seeders` directory.
Comprehensive Answer
What is Middleware in Laravel?
BeginnerMiddleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that ...
Comprehensive Answer
What are Route Parameters?
BeginnerRoute parameters allow you to capture segments of the URI within your route. They are always encased within `{}` braces.
Comprehensive Answer
PHP/Laravel Example
Route::get('/user/{id}', function ($id) { return 'User '.$id; });What is the use of `dd()` in Laravel?
Beginner`dd()` stands for 'Dump and Die'. It dumps the given variables and ends the execution of the script. It is heavily used for debugging.
Comprehensive Answer
How do you configure database connections in Laravel?
BeginnerDatabase configuration is handled primarily in the `.env` file at the root of the project, mapping to the `config/database.php` configuration file.
Comprehensive Answer
What is Eloquent ORM?
BeginnerEloquent is Laravel's Object-Relational Mapper (ORM). It provides an active record implementation for working with your database. Each database table has a corr...
Comprehensive Answer
How do you define an Artisan command?
BeginnerYou can create an Artisan command using `php artisan make:command NameCommand`. The logic goes into the `handle` method of the generated class.
Comprehensive Answer
What is the `public` directory used for?
BeginnerThe `public` directory contains the `index.php` file, which is the entry point for all requests entering your application. It also houses your assets such as im...
Comprehensive Answer
How to pass data to a View?
BeginnerYou can pass an array of data as the second argument to the `view` helper function, or use the `with` method.
Comprehensive Answer
PHP/Laravel Example
return view('greetings', ['name' => 'Victoria']);What is a Service Provider?
BeginnerService providers are the central place of all Laravel application bootstrapping. Your application, as well as all of Laravel's core services, are bootstrapped ...
Comprehensive Answer
How to handle form validation?
BeginnerLaravel provides several different approaches to validate your application's incoming data, such as the `validate` method available on all incoming HTTP request...
Comprehensive Answer
PHP/Laravel Example
$request->validate(['title' => 'required|unique:posts|max:255']);Explain Dependency Injection in Laravel.
IntermediateDependency Injection is a design pattern used to pass dependencies into a class rather than having the class create them. Laravel's Service Container natively h...
Comprehensive Answer
What is the Service Container?
IntermediateThe Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Binding and resolving are its core feature...
Comprehensive Answer
What is a Facade in Laravel?
IntermediateFacades provide a "static" interface to classes that are available in the application's service container. They serve as "proxies" to underlying classes in the ...
Comprehensive Answer
How do Eloquent Relationships work?
IntermediateEloquent relations are defined as methods on your Eloquent model classes. Types of relationships include: One To One, One To Many, Many To Many, Has One Through...
Comprehensive Answer
Explain the `with()` method (Eager Loading) in Eloquent.
IntermediateWhen accessing Eloquent relationships as properties, the relationship data is "lazy loaded". Eager loading (`with`) alleviates the N+1 query problem by fetching...
Comprehensive Answer
What are Accessors and Mutators?
IntermediateAccessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. (e.g., getting a user's first and last na...
Comprehensive Answer
What are Form Requests?
IntermediateForm requests are custom request classes that encapsulate their own validation and authorization logic. You create them using `php artisan make:request`.
Comprehensive Answer
What is Mass Assignment vulnerability and how does Laravel prevent it?
IntermediateMass assignment is when HTTP request parameters are used to blindly update or create a Model. Laravel protects against this using the `$fillable` or `$guarded` ...
Comprehensive Answer
What are Eloquent Collections?
IntermediateAll multi-result sets returned by Eloquent are instances of the `Illuminate\Database\Eloquent\Collection` object. Collections provide dozens of methods for eleg...
Comprehensive Answer
What is Route Model Binding?
IntermediateWhen injecting a model ID to a route or controller action, Route Model Binding automatically injects the model instance containing that ID directly into your ro...
Comprehensive Answer
PHP/Laravel Example
Route::get('/users/{user}', function (User $user) { return $user->name; });What are Laravel Events and Listeners?
IntermediateLaravel's events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Listeners res...
Comprehensive Answer
What are Laravel Jobs and Queues?
IntermediateQueues allow you to defer the processing of a time-consuming task, such as sending an email, until a later time. This drastically speeds up web requests to your...
Comprehensive Answer
What is caching in Laravel?
IntermediateLaravel provides a unified API for various caching systems like Memcached and Redis. Caching allows you to store frequently accessed data for fast retrieval.
Comprehensive Answer
What is an API Resource in Laravel?
IntermediateWhen building an API, you may need a transformation layer between your Eloquent models and the JSON responses returned to your users. API resources allow you to...
Comprehensive Answer
What is `SoftDeletes` trait?
IntermediateWhen models are soft deleted, they are not actually removed from your database. Instead, a `deleted_at` attribute is set on the model.
Comprehensive Answer
How does Session management work in Laravel?
IntermediateSince HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. Laravel supports various sess...
Comprehensive Answer
Explain Request Lifecycle in Laravel.
IntermediateEntry point -> `public/index.php` -> Http Kernel -> Service Providers bootstrapped -> Router -> Middleware -> Controller -> View -> Response.
Comprehensive Answer
What is the difference between `Query Builder` and `Eloquent`?
IntermediateThe Query Builder provides a fluent interface to creating and running simple and advanced database queries. Eloquent is an ORM built heavily on top of the Query...
Comprehensive Answer
What are Laravel Policies?
IntermediatePolicies are classes that organize authorization logic around a particular model or resource. For example, a `PostPolicy` might authorize who can create, update...
Comprehensive Answer
What is the difference between `Cache::put()` and `Cache::remember()`?
Intermediate`put` simply sets a value in the cache. `remember` will retrieve an item from cache, but if it doesn't exist, it will execute the provided closure, store its ou...
Comprehensive Answer
What is Laravel Telescope?
IntermediateTelescope is an elegant debug assistant for the Laravel framework. It provides insight into requests, exceptions, log entries, database queries, queued jobs, ma...
Comprehensive Answer
Explain Database Transactions in Laravel.
IntermediateYou may use the `transaction` method on the `DB` facade to run a set of operations within a database transaction. If an exception is thrown within the transacti...
Comprehensive Answer
What is a polymorphic relationship?
IntermediateA polymorphic relationship allows the target model to belong to more than one type of model using a single association. For example, a `Comment` model might bel...
Comprehensive Answer
What are Observers in Laravel?
IntermediateIf you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observers have method names tha...
Comprehensive Answer
What is Route Grouping?
IntermediateRoute groups allow you to share route attributes, such as middleware, controllers, or prefixes, across a large number of routes without needing to define those ...
Comprehensive Answer
How does the Service Container resolve dependencies deeply?
AdvancedUsing PHP's reflection mechanism (Reflection API), Laravel inspects the type hints of the constructed class. It recursively resolves dependencies required by th...
Comprehensive Answer
What is the difference between `bind`, `singleton`, and `instance` in Service Container?
Advanced`bind` resolves a new instance every time. `singleton` resolves the same instance on subsequent calls after the first resolution. `instance` binds an already ex...
Comprehensive Answer
Explain Deferred Service Providers.
AdvancedIf your provider is strictly registering bindings in the container, you can defer its registration until one of the bindings is requested, improving the applica...
Comprehensive Answer
How does Macroable trait work in Laravel?
AdvancedThe `Macroable` trait allows expanding classes at runtime by injecting new methods via closures. Many Laravel components (Response, Request, Collection) use it,...
Comprehensive Answer
Explain the Pipeline Pattern in Laravel Middleware.
AdvancedLaravel Middleware sits on top of the `Illuminate\Pipeline\Pipeline` class. It passes the request through an array of closures/classes. Each has the opportunity...
Comprehensive Answer
What is Eloquent Global Scopes?
AdvancedGlobal scopes allow you to add constraints to all queries for a given model. Laravel's own `SoftDeletes` feature utilizes a global scope to only pull non-delete...
Comprehensive Answer
How does Laravel Octane improve performance?
AdvancedOctane boots your application once using high-performance application servers like Swoole or RoadRunner, keeping it in memory. Subsequent incoming requests are ...
Comprehensive Answer
What are Custom Casts in Eloquent?
AdvancedLaravel has built-in casts (`array`, `json`, `date`). Custom Casts allow you to define a class that handles the serialization/deserialization logic for custom v...
Comprehensive Answer
Explain Broadcasting in Laravel.
AdvancedBroadcasting allows you to share events between your server-side code and your client-side JavaScript applications over WebSockets using drivers like Pusher or ...
Comprehensive Answer
What are Queued Event Listeners?
AdvancedInstead of executing an event listener synchronously during the request, you can implement the `ShouldQueue` interface on the listener. Laravel will automatical...
Comprehensive Answer
How to handle Multi-tenancy in Laravel?
AdvancedMulti-tenancy can be handled via single database (filtering scopes per tenant ID) or multi-database schemas (dynamic database connections resolved via middlewar...
Comprehensive Answer
What are Database locking mechanisms in Laravel?
AdvancedLaravel provides 'Pessimistic Locking' via `sharedLock()` and `lockForUpdate()` query builder methods. 'Optimistic Locking' is generally implemented manually vi...
Comprehensive Answer
Explain Laravel Horizon.
AdvancedHorizon provides a beautiful dashboard and code-driven configuration for Laravel-powered Redis queues. It allows you to monitor key metrics such as job throughp...
Comprehensive Answer
How to handle heavy polymorphic querying efficiently?
AdvancedUse `morphTo` and `morphMany`. For deeply nested polymorphic queries, ensure you eager load using `with(['morphable' => function() {...}])` to avoid N+1 queries...
Comprehensive Answer
Explain CSRF bypass and safety in stateful vs stateless APIs.
AdvancedCSRF is only required for cookie-based stateful sessions. Stateless APIs using tokens (Bearer headers or Sanctum SPAs) don't naturally suffer from CSRF, though ...
Comprehensive Answer
What are the advantages of using UUID/ULID over incremental IDs?
AdvancedUUIDs/ULIDs prevent ID enumeration attacks (guessing URLs), allow offline ID generation (helpful for mobile apps/distributed systems), and are required in horiz...
Comprehensive Answer
Deep Dive into Laravel Reverb.
AdvancedReverb is a first-party, scaleable WebSocket server for Laravel 11. It's built for speed using PHP's async capabilities and integrates perfectly with Laravel's ...
Comprehensive Answer
How does Laravel chunking handle large datasets?
Advanced`chunk()` retrieves a limited chunk of records, runs a closure over them, then retrieves the next chunk. This drastically reduces memory usage when processing t...
Comprehensive Answer
What is `chunkById()` and why is it safer than `chunk()` when updating?
AdvancedIf you update a field that the query is filtering/ordering by, `chunk()` will skip records due to offset shifting. `chunkById()` pages using the primary key (`w...
Comprehensive Answer
How does the Task Scheduling (`schedule` method) work under the hood?
AdvancedA single cron entry calls `php artisan schedule:run` every minute. Laravel then evaluates all scheduled tasks in the `routes/console.php` (or Kernel) file, exec...
Comprehensive Answer
What is `tap()` helper function?
Advanced`tap` accepts a value and a closure. It executes the closure with the value, then returns the value. It's useful for chained method calls without needing to ass...
Comprehensive Answer
Deep dive on Eloquent serialization.
AdvancedWhen casting Models to arrays or JSON, Laravel checks for hidden or appended attributes. Accessors are converted, mutators applied. It implements `JsonSerializa...
Comprehensive Answer
Explain Repository Pattern vs Active Record in Laravel.
AdvancedEloquent is an Active Record implementation (Model contains data AND DB logic). The Repository pattern abstracts data access to interchangeable classes. While R...
Comprehensive Answer
What is Laravel Sanctum vs Passport?
AdvancedPassport provides a full OAuth2 server implementation. Sanctum provides a featherweight authentication system for SPAs, mobile apps, and simple API token issuan...
Comprehensive Answer
How would you structure a highly complex domain in Laravel?
AdvancedUsing Domain-Driven Design (DDD) principles. Moving away from standard MVC arrays to modules or bounded contexts (e.g., separating `app/Domain`, `app/Infrastruc...
Comprehensive Answer
Write a Route that returns a given user ID.
ProgrammingRoute parameter definition.
Comprehensive Answer
PHP/Laravel Example
Route::get('/users/{id}', function ($id) {
return 'User ID: ' . $id;
});Create a Query to fetch users with more than 5 posts.
ProgrammingUse `has()` relationship method.
Comprehensive Answer
PHP/Laravel Example
User::has('posts', '>', 5)->get();How to use Eloquent to mass update records?
ProgrammingCall update on the query builder directly.
Comprehensive Answer
PHP/Laravel Example
User::where('status', 'inactive')->update(['status' => 'archived']);Write an Eloquent Mutator for 'first_name'.
ProgrammingIn Laravel 9+ using the new syntax.
Comprehensive Answer
PHP/Laravel Example
protected function firstName(): Attribute {
return Attribute::make(
set: fn (string $value) => strtolower($value),
);
}Write an Eloquent Accessor derived from multiple fields.
ProgrammingCombining first and last name.
Comprehensive Answer
PHP/Laravel Example
protected function fullName(): Attribute {
return Attribute::make(
get: fn () => $this->first_name . ' ' . $this->last_name,
);
}Define a One-to-Many Relationship in a Model.
ProgrammingA Post has many Comments.
Comprehensive Answer
PHP/Laravel Example
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}How to validate a required, unique email in a FormRequest?
ProgrammingUsing rules method.
Comprehensive Answer
PHP/Laravel Example
public function rules() {
return [
'email' => 'required|email|unique:users,email'
];
}How to use implicit Route Model Binding?
ProgrammingType hint the Model in the controller.
Comprehensive Answer
PHP/Laravel Example
public function show(User $user) {
return view('user.show', compact('user'));
}Write a DB Transaction example.
ProgrammingUsing DB facade.
Comprehensive Answer
PHP/Laravel Example
DB::transaction(function () {
User::create([...]);
Profile::create([...]);
});How to fetch soft deleted records using Eloquent?
ProgrammingUse the withTrashed method.
Comprehensive Answer
PHP/Laravel Example
User::withTrashed()->where('id', 1)->first();Implement caching for a database query.
ProgrammingUsing Cache::remember.
Comprehensive Answer
PHP/Laravel Example
$users = Cache::remember('users', 3600, function () {
return User::all();
});How to dispatch a Job to a specific queue?
ProgrammingUsing the onQueue method.
Comprehensive Answer
PHP/Laravel Example
ProcessPodcast::dispatch($podcast)->onQueue('processing');Log a custom warning message.
ProgrammingUsing the Log facade.
Comprehensive Answer
PHP/Laravel Example
Log::warning('Something could be going wrong', ['user' => $user->id]);Redirect back with input and errors.
ProgrammingCommon in controller form submissions.
Comprehensive Answer
PHP/Laravel Example
return back()->withInput()->withErrors(['error' => 'Invalid data.']);How to eager load nested relationships?
ProgrammingUse dot notation.
Comprehensive Answer
PHP/Laravel Example
Book::with('author.contacts')->get();Generate a URL for a named route with parameters.
ProgrammingUsing the route helper.
Comprehensive Answer
PHP/Laravel Example
$url = route('profile', ['id' => 1]);How to authenticate a user manually?
ProgrammingUsing Auth attempt.
Comprehensive Answer
PHP/Laravel Example
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('dashboard');
}How to update a JSON column using Eloquent?
ProgrammingUpdate deeply nested JSON properties.
Comprehensive Answer
PHP/Laravel Example
User::where('id', 1)->update(['meta->theme' => 'dark']);Create a Global Scope to only get active users.
ProgrammingDefine and apply.
Comprehensive Answer
PHP/Laravel Example
protected static function booted() {
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('active', 1);
});
}Send an existing Mailable class.
ProgrammingUsing Mail facade.
Comprehensive Answer
PHP/Laravel Example
Mail::to($request->user())->send(new OrderShipped($order));How to check if a collection contains a specific value?
ProgrammingUsing the contains method.
Comprehensive Answer
PHP/Laravel Example
if ($collection->contains('Desk')) { ... }Write an API Resource that hides a column.
ProgrammingIn the toArray method.
Comprehensive Answer
PHP/Laravel Example
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
// token omitted
];
}Upload and store a file to the public disk.
ProgrammingUsing the store method on the uploaded file.
Comprehensive Answer
PHP/Laravel Example
$path = $request->file('avatar')->store('avatars', 'public');Query records created in the last 7 days.
ProgrammingUsing Carbon or whereDate.
Comprehensive Answer
PHP/Laravel Example
User::where('created_at', '>=', now()->subDays(7))->get();Run an Artisan command programmatically.
ProgrammingUsing Artisan::call.
Comprehensive Answer
PHP/Laravel Example
Artisan::call('email:send', ['user' => 1, '--queue' => 'default']);