What Laravel is
TipIt favours convention over configuration. Eloquent is the ORM, Blade the template engine and Artisan the command-line tool.
Asked in interviews
AskedWhat is Laravel and what are its key features?public/index.php , boots the app, passes through middleware to a route, and returns through the same middleware.register() binds services, then every boot() can safely use them.N+1 starts.Cache::get() looks static, but a facade fetches the real object from the container and calls it.terminate() runs AFTER.TipIt favours convention over configuration. Eloquent is the ORM, Blade the template engine and Artisan the command-line tool.
Asked in interviews
AskedWhat is Laravel and what are its key features?composer.lockcomposer installcomposer updatecomposer require <pkg>TipComposer also builds the PSR-4 autoloader, so classes load from their file paths with no require.
Asked in interviews
AskedWhat is Composer and how is it used in Laravel?public/index.php terminate()Tipbootstrap/ creates the app, which is also the container. The kernel then loads config and runs every register() and boot().
$this->app->bind(A::class, B::class)$this->app->singleton(A::class, B::class)__construct(private Repo $repo)show(Request $r, User $user)TipA concrete class needs no binding. Bind an interface to swap the class, or a test fake, in one place.
TrapIn a controller method, list injected dependencies before route parameters.
register()boot()TipYour own setup usually goes in App. A deferred provider loads only when a binding is first requested.
Asked in interviews
AskedExplain Service Providers in LaravelCache::shouldReceive('get') Tip__callStatic() asks get for a binding name, resolves that object and calls get() on it.
TrapA facade needs no constructor, so a class can depend on many services without showing it. This is scope creep.
Asked in interviews
AskedWhat are facades in Laravel and how do they work?Collection::macro('up', $fn)Collection::hasMacro('up') composer.jsonextra.laravel.providers TipAny class with the Macroable trait accepts a macro. Register it in a provider's boot().
TrapA later macro with the same name replaces the earlier one with no warning.
Route::get('/users', [UserController::class, 'index'])php artisan route:listroutes/api.php (11+)php artisan install:api/user/{id}/hello/{name?}404 if it fails->where('id', '[0-9]+')Tipweb.php routes get sessions and cross-site request forgery (CSRF) protection. api.php routes get the /api prefix.
TrapLaravel passes parameters in order, so arguments must follow the placeholders. An optional one needs a default value.
Route::middleware('auth')->group($fn)Route::prefix('admin')->name('admin.'){post}, 404 if nonefn (Post $post) => $post/posts/{post:slug} Trap{post} binds only to a variable named $post.
php artisan make:controller PostController --resourceRoute::resource('posts', PostController::class) TipThe seven are index, create, store, show, edit, update and destroy. Route::api leaves out create and edit.
Asked in interviews
AskedWhat are resource controllers and how do they work?return $next($request)bootstrap/app.php (11+)$middleware->append(A::class)$middleware->alias(['sub' => A::class])->middleware('sub')->withoutMiddleware('sub') app/Http/Kernel.php app(Pipeline::class)->send($v)->through($pipes)->thenReturn() TipCode before $next() runs on the way in. Code after it can change the response on the way out.
TrapYou can't skip global middleware per route. Only route middleware has without.
$request->validate(['a' => 'required|max:255'])php artisan make:request StorePost$request->validated()php artisan make:rule UppercaseTipOn failure, a form redirects back with errors and old input. A request that expects JSON gets a 422.
Asked in interviews
AskedHow do you handle validation in Laravel?User::where('active', 1)->get()DB::table('users')->get()TipEloquent also gives you relationships, timestamps, soft deletes, scopes and events.
Asked in interviews
AskedWhat is Eloquent ORM and its advantages?hasOne(Phone::class) hasMany(Post::class) belongsTo(User::class) belongsToMany(Role::class) hasManyThrough(A::class, B::class)morphTo()TipThe default pivot table is role_user. $user->posts() builds a query, and $user->posts loads rows.
Asked in interviews
AskedExplain Eloquent relationshipsPost::with('user')->get()$posts->load('user')Model::preventLazyLoading() Tipwith() fetches every related row in one WHERE id IN (...) query.
TrapReading $post->user in a loop runs one query per post.
Asked in interviews
AskedWhat is the N+1 query problem and how do you solve it?Attribute::make(get: $g, set: $s)getNameAttribute() setNameAttribute() scopeActive($query) User::active()static::addGlobalScope('a', $fn)withoutGlobalScope('a') TrapFor JSON to an array, a cast is shorter than an accessor.
use SoftDeletes;$table->softDeletes(); Post::withTrashed() Post::onlyTrashed() $post->restore()$post->forceDelete() Tipdelete() runs an UPDATE that fills deleted_at, and a global scope hides those rows.
TrapA unique index on email still counts trashed rows. Laravel doesn't soft delete related models for you.
Asked in interviews
AskedHow does soft delete work in Laravel?$fillable = ['name']$guarded = ['is_admin']User::create($request->validated())TrapFields outside $fillable are dropped with no error. $user->is_admin = true is never blocked.
Asked in interviews
AskedWhat is mass assignment and how does Laravel protect against it?creatingcreatedUser::observe(UserObserver::class) Tipsaving and saved fire on every save, even when nothing changed.
TrapPost::where(...)->delete() never loads the models, so it fires no delete events.
Asked in interviews
AskedWhat are model events in Laravel?php artisan migratephp artisan migrate:rollbackphp artisan migrate:freshUser::factory(10)->create()DatabaseSeederphp artisan db:seedTipup() applies a change and down() reverses it.
TrapNever edit a migration that already ran in production. Add a new one.
A plain job can run before the commit and read old data. With afterCommit(), the delayed job waits for the commit.
DB::transaction($fn, 3)DB::beginTransaction() Job::dispatch()->afterCommit() DB::afterCommit($fn) TipThe closure commits on return and rolls back on an exception. Nested transactions use savepoints.
Asked in interviews
AskedHow do you use database transactions in Laravel?collect($a)->filter($f)->sum()LazyCollection::make($gen) User::cursor()User::lazy()TipA chain reads top to bottom. array_filter() and array_map() nest, and take their arguments in different orders.
Trapcursor() can't eager load, and PDO may still buffer every raw row. A huge table can still exhaust memory.
{{ $name }}{!! $html !!}@yield('title', 'Default')@extends('layouts.app') @section('title', 'Posts')TipBlade compiles each template to plain PHP and caches it until the template changes.
Trap{!! !!} skips escaping, so user data there allows cross-site scripting (XSS), a script injected into the page.
view('home', compact('user'))View::composer('home', $fn)View::share('name', $v)<x-alert type="error" :open="true">{{ $slot }}{{ $attributes }}TipA colon prefix passes a PHP expression. An anonymous component is only a Blade file, with no class.
401Auth::attempt($credentials)403can:edit,postconfig/auth.php$request->session()->regenerate()TipAuthentication checks who you are, and authorization checks what you may do. Authentication comes first.
TrapIf you don't regenerate the session, an attacker can plant a known session ID before login. This is session fixation.
boot()Gate::define('edit', $fn)403 responseGate::allows('edit', $post)Gate::authorize('edit', $post)php artisan make:policy PostPolicy --model=Post$user->can('edit', $post)@can('edit', $post)TipUse a gate for an action with no model, and a policy for one model's rules. A policy's before() can allow admins everything.
$user->createToken('name')->plainTextToken TipUse Sanctum when you control the clients, and Passport only for a full OAuth server for third-party apps.
Asked in interviews
AskedWhat is Laravel Sanctum and when should you use it?@csrfsame-origin requests with no token (13)Sec-Fetch-Site$middleware->preventRequestForgery(except: ['stripe/*'])Hash::make($password)TipAnother site can make a browser submit a form, but it can't read the token. A mismatch returns 419.
TrapEloquent and the query builder bind parameters with PDO. Raw SQL with user input can still allow SQL injection.
new PostResource($post) PostResource::collection($page) ->middleware(['auth:sanctum', 'throttle:60,1'])Route::prefix('v1')->name('v1.')TipA header version keeps URLs clean, but it's harder to test, cache and read in logs. So URL versions are more common.
TrapWithout a name prefix, both versions register posts.index, so route:cache fails.
$this->get('/a')->assertStatus(200) $this->assertDatabaseHas('posts', $row)use RefreshDatabase; Mail::fake()Queue::fake()Tipphp artisan test runs Pest or PHPUnit. The kinds are unit, feature and browser tests with Laravel Dusk, and the docs advise mostly feature tests.
TrapUnit tests don't boot Laravel, so they can't use the database or factories.
Asked in interviews
AskedWhat types of testing does Laravel support?Pod::dispatch($p)->delay(now()->addMinutes(10)) ->onQueue('mail') failed_jobsphp artisan queue:work --tries=3database by default, or Redis for high volume.Bus::batch($jobs)->dispatch()TipBatched jobs need the Batchable trait. One failed job cancels the batch by default, unless you call allowFailures().
TrapA worker keeps the booted app in memory, so it runs old code until queue:restart. Keep it running with Supervisor.
event(new Shipped($order))$listenEventServiceProvider implements ShouldBroadcastbroadcastAs() name, with a leading dotEcho.channel('orders').listen('.order.shipped', cb)routes/channels.php new PrivateChannel('o.1') TipLaravel finds listeners by scanning app/Listeners. A listener that implements ShouldQueue runs on the queue.
TrapBroadcasting goes through the queue to a server such as Laravel Reverb, so a queue worker must be running.
routes/console.php (11+)Schedule::command('send')->daily()* * * * * cd /path && php artisan schedule:run->withoutOverlapping() ->onOneServer()TipA long task should dispatch a queued job, so it doesn't delay the other tasks.
Asked in interviews
AskedHow does task scheduling work in Laravel?Cache::remember('k', 3600, $fn)Cache::put('k', $v, $secs)Cache::flexible('k', [5, 10], $fn)php artisan route:cachephp artisan route:clearTipSwitch stores in config. New apps use the database store. File, database and DynamoDB stores don't support tags.
TrapThe route cache is a snapshot. Laravel ignores route file changes until you rebuild it, so leave it off locally.
TipSelect only the columns you need, and index the ones in WHERE, JOIN and ORDER BY. Enable OPcache on the server.
TrapUnder Octane, state in singletons or static properties leaks between requests. Reset it on each request.
Asked in interviews
AskedWhat are some Laravel performance optimization techniques?composer install --optimize-autoloader --no-devphp artisan migrate --forcephp artisan optimizeAPP_DEBUG=falsephp artisan key:generateTrapA new APP_KEY breaks encrypted data and sessions. After config:cache, env() returns null outside config files.
Asked in interviews
AskedWhat are the key steps for deploying a Laravel application?Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in