55 Laravel interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
Laravel is a PHP framework that bundles routing, the Eloquent ORM, queues, and many other building blocks for web applications. Questions here look at the service container and service providers, Eloquent relationships including polymorphic ones, validation, queue jobs and failure handling, CSRF protection, caching, task scheduling, file uploads and storage, and the repository pattern.
and 7 more topics.
Laravel is an MVC PHP framework that bundles what every web app needs: routing, database access, templating, authentication, validation, queues and testing. That way you do not rebuild these pieces in every project. The route receives /posts/5; Laravel sees a Post-typed parameter, so it queries…
Routing connects a URL + HTTP method to the code that handles it, usually a controller method. Routes for the web UI are declared in routes/web.php. - Method + URL: GET /users calls index, POST /users uses the same URL but calls store. There are…
Blade is Laravel's template engine: a .blade.php file in resources/views is HTML plus a few directives starting with @, without scattering <?php ... ? everywhere. Blade compiles each template into plain PHP and caches it until the file is modified, so it adds almost no…
Migrations are version-controlled database schema definitions. Create one with php artisan make:migration createuserstable, define the table in up() and the rollback in down(): Run every pending migration with php artisan migrate. Advantages: schema changes tracked in version control, easy rollback, consistency across environments, and the…
MVC splits an application into three parts so that each one has a single job: the Model works with data and the database, the View is the interface that is displayed, and the Controller receives the request and coordinates between the other two. The flow…
Artisan is Laravel's command-line interface for common tasks. Essential commands: - php artisan migrate: run database migrations - php artisan make:controller UserController: create a controller - php artisan make:model User: create a model - php artisan serve: start the development server - php artisan tinker:…
A controller holds the request logic for one resource (User, Product): it takes the request, works with the Model, and returns a View or JSON. php artisan make:controller ProductController --resource scaffolds the CRUD methods — index() (list), show($id) (one record), create() (create form), store() (save…
Dependency injection automatically provides required dependencies to classes. Instead of new UserRepository() inside the controller, type-hint it in the method: Laravel's service container automatically instantiates and injects the class. Benefits: easier testing (inject mock repository), loose coupling (change implementation without modifying controller), cleaner code. Laravel…
A Service Provider is where a Laravel app declares how services are built in the service container (the registry Laravel asks whenever it needs to inject a dependency) and runs setup code at boot time. Every provider has two methods, register() and boot(). At startup…
Validation in Laravel means declaring rules per field (required, email, max:100…) and letting the framework check them before the data reaches your logic. The shortest way is $request-validate([...]) inside the controller; for larger forms move it into a Form Request to keep the controller clean.…
Eloquent is Laravel's Active Record ORM: each table has a Model class, each row is an object, and you query with methods instead of SQL strings. It is not "better" than raw SQL in every way; it is fast for CRUD and relationships, while raw…
A Laravel model is an Eloquent class that represents a table: each object is a row and each attribute is a column. You read and write data through the model instead of hand-written SQL. Create one with php artisan make:model Post -m (the -m flag…
An Eloquent relationship is a model method that declares how two tables are linked by a foreign key. You declare it once, then fetch related data with $user-posts instead of writing a JOIN yourself. The main types: - hasOne / belongsTo: one-to-one. The side that…
An N+1 query problem is when you run 1 query for a list of parents and then one more query per record to fetch a relationship. 100 users become 101 queries. It happens because Eloquent relationships are lazy loaded by default: $user-posts only queries the…
A query scope is a query condition given a name inside the model so it can be reused instead of repeating where(...) in many places. There are two kinds. A local scope applies when you call it. Declare it with the [Scope] attribute (Laravel 12.4…
An accessor transforms data on read, a mutator transforms it on write. Both are declared with Attribute::make(): Assigning $user-email = "JOHN@EXAMPLE.COM" stores it lowercased, while echo $user-name prints it capitalized even though the DB holds lowercase. Accessors and mutators keep formatting logic in one place.
Soft delete marks records as deleted without removing them from the database. The model uses the SoftDeletes trait and the migration adds a deletedat column: Every Eloquent query automatically adds deletedat IS NULL (a global scope), so existing code keeps working. Queries written with DB::table()…
Factories generate fake data for tests; create one with php artisan make:factory UserFactory. The model must use the HasFactory trait for User::factory() to work. Seeders populate the database: php artisan make:seeder UserSeeder, and inside run() call User::factory(100)-create(). By default php artisan db:seed runs only DatabaseSeeder.…
Query builder is a fluent interface for building queries without raw SQL. Example: Advantages: database-agnostic (easily switch databases), prevents SQL injection because values are sent through PDO parameter binding (the SQL uses ? placeholders and values travel separately, so they are never parsed as SQL),…
Laravel Reverb is Laravel's first-party WebSocket server, launched with Laravel 11 (the package runs on Laravel 10.47 and later), used to broadcast real-time events such as notifications or chat. Unlike Pusher, which is a paid third-party service, Reverb is open source and you host it…
Pennant is Laravel's official feature flag package (install separately: composer require laravel/pennant, available since Laravel 10) for turning features on and off per user or group. It supports closure-based flags and class-based flags (a resolve method). Example: In Blade, use @feature('new-checkout') ... @else ... @endfeature.…
Pest is a PHP testing framework that runs on top of PHPUnit. Instead of writing a class with test... methods, each test is a closure passed to test() or it(), and you assert with an expect() chain. Inside the closure, $this is still Laravel's TestCase,…
Sanctum is a lightweight auth package for your own apps: SPAs and mobile apps. Passport is a full OAuth 2.0 server, used when third parties need to request access to your users' data, like "Sign in with GitHub". Sanctum authenticates in two ways: - SPA…
API Resources are a layer that turns Eloquent models into JSON responses with a fixed shape, decoupling the API format from the database schema. A resource returns exactly the fields you list in toArray(). It does not hide anything automatically: a sensitive field like password…
In Laravel the key difference is whether the application boots. A feature test (tests/Feature) extends Tests\TestCase, boots the whole app, and sends a fake request through routes, middleware, validation and controllers down to the database. A unit test (tests/Unit) extends PHPUnit\Framework\TestCase directly, does not boot…
CSRF (Cross-Site Request Forgery) = an attacker tricks a victim’s browser — already logged into your site — into firing a state-changing request (transfer money, change email). The browser auto-attaches the session cookie, so the server thinks it is a genuine user action. Prevention per…
Per Fowler (PoEAA), a Repository mediates between the domain and the data-mapping layer, exposing a collection-like API (find, save, findByEmail) and hiding the Eloquent/SQL details underneath. Business logic talks only to the repository, never writing queries directly. - Benefits: decouples logic from the ORM, eases…
Laravel offers one unified Cache API across multiple drivers (stores): file, database, redis, memcached, array (for tests), null. Configured in config/cache.php — switching backends requires no code change. - Cache tags group keys so you can flush them together: Cache::tags(['posts'])-put(...) then Cache::tags(['posts'])-flush(). Only redis/memcached support…
Instead of scattering messy cron lines on the server, Laravel lets you define the schedule in code in routes/console.php (or the Kernel’s schedule() in older versions). On the server you need just one cron entry on the server running every minute; Laravel decides which tasks…
Laravel’s Filesystem (built on Flysystem) abstracts multiple "disks" — local, public, s3... — configured in config/filesystems.php, with the same Storage API for every disk. Moving from local to S3 requires no business-code change. - Validate before storing: rules file, image, mimes:jpg,png, max:2048 (in KB). -…
They run in two different phases of the application bootstrap. - register() runs first, for every provider. It should only bind into the container (bind, singleton, scoped). Never touch another provider's services here — they may not be registered yet. - boot() runs after all…
A Form Request is a class extending FormRequest that moves validation rules and authorization out of the controller. Laravel resolves it from the type-hint and validates before the controller body runs; on failure it redirects with errors (web) or returns 422 JSON (API). Benefits: thin…
They differ in the lifetime of the object the container hands back. - bind — resolves a new instance every time. Use for objects that carry per-use state. - singleton — resolves once; later calls return the same object for the whole process lifetime. Good…
Route model binding makes Laravel query the model automatically from a route parameter and inject it into the controller; if nothing is found it returns 404. Bind by another column — declare it on the route or override getRouteKeyName() on the model: Scoped binding —…
A polymorphic relationship lets one model belong to several parent types through a single relation. The child table keeps two columns: id (parent key) and type (parent class name). Classic case: comments attach to both Post and Video; same for images, likes, activitylogs. Eager loading…
Both go through an intermediate table, but they mean different things. - belongsToMany — a many-to-many relation whose intermediate table is a pivot with no model of its own (roleuser). Pivot columns are reachable via withPivot(). - hasManyThrough — a one-to-many that passes through a…
Three tiers, chosen by how complex the transformation is. 1. Built-in casts — declared in casts() for common types. This is where datetime, boolean, array, encrypted, and PHP 8.1 backed enums belong: 2. Accessor / mutator via Attribute — custom logic applied when reading or…
A job fails when it throws an uncaught exception and has exhausted its attempts. Laravel then writes a row to the failedjobs table and stops retrying it. The knobs: - $tries on the job takes precedence over the worker's --tries flag. - If $backoff is…
An Observer hooks into one Eloquent model's lifecycle. Laravel calls creating, created, updating, updated, deleting, deleted, restored automatically whenever that model is touched — nothing is dispatched by hand. Events/Listeners are the general mechanism: you define the event, dispatch it yourself, many listeners can subscribe,…