Title: Laravel Framework — LearnCoachAssist

Q: What is Laravel Eloquent ORM?
A: Eloquent is Laravel's built-in Active Record ORM. Each database table has a corresponding Model class used to interact with that table. It provides an expressive syntax for queries:
$users = User::where('active', true)->get();

Q: How do you define a one-to-many relationship in Eloquent?
A: In the parent model, define a method returning hasMany():
public function posts() { return $this->hasMany(Post::class); }
In the child model, define the inverse with belongsTo():
public function user() { return $this->belongsTo(User::class); }

Q: What is eager loading in Eloquent and why is it important?
A: Eager loading solves the N+1 query problem by loading relationships upfront:
$books = Book::with('author')->get();
Without it, accessing a relationship in a loop triggers a separate query per iteration, causing performance issues.

Q: How do you create a new Eloquent model and migration together?
A: Use the Artisan command:
php artisan make:model Post -m
The -m flag generates a migration file alongside the model. You can also add -f for a factory and -s for a seeder.

Q: What are Eloquent accessors and mutators?
A: Accessors transform attribute values when reading:
protected function firstName(): Attribute { return Attribute::make(get: fn($value) => ucfirst($value)); }
Mutators transform values when setting:
set: fn($value) => strtolower($value)

Q: What is the purpose of Blade templates in Laravel?
A: Blade is Laravel's templating engine. It provides convenient shortcuts for PHP control structures and template inheritance:
- {{ $var }} — escaped output
- @if, @foreach — control directives
- @extends, @section, @yield — layout inheritance

Q: How do you pass data to a Blade view?
A: You can pass data in several ways:
- return view('profile', ['user' => $user]);
- return view('profile')->with('user', $user);
- return view('profile', compact('user'));
All make $user available in the template.

Q: What is the difference between {{ }} and {!! !!} in Blade?
A: {{ $var }} applies htmlspecialchars to escape output, preventing XSS attacks.
{!! $var !!} outputs raw, unescaped HTML. Only use {!! !!} when you trust the content completely.

Q: How do you create a Blade component?
A: Use Artisan:
php artisan make:component Alert
This creates a class at app/View/Components/Alert.php and a Blade file at resources/views/components/alert.blade.php. Use it with:
<x-alert type="error" :message="$msg" />

Q: How do you define a basic route in Laravel?
A: Routes are defined in routes/web.php or routes/api.php:
Route::get('/welcome', function () { return view('welcome'); });
You can also point to a controller:
Route::get('/users', [UserController::class, 'index']);

Q: What are route parameters in Laravel?
A: Route parameters capture segments of the URI:
Required: Route::get('/user/{id}', ...)
Optional: Route::get('/user/{name?}', ...)
Parameters are passed as arguments to the closure or controller method.

Q: What is route model binding in Laravel?
A: Laravel can automatically inject model instances matching route parameters:
Route::get('/posts/{post}', function (Post $post) { return $post; });
If the type-hinted variable matches the parameter name, Laravel resolves it by primary key automatically. Use getRouteKeyName() to customize.

Q: How do you name a route and why?
A: Named routes let you generate URLs and redirects without hard-coding paths:
Route::get('/dashboard', [DashController::class, 'index'])->name('dashboard');
Generate URLs with:
route('dashboard')
Redirect with:
return redirect()->route('dashboard');

Q: What is a resource controller in Laravel?
A: A resource controller handles all CRUD routes for a resource. Create with:
php artisan make:controller PhotoController --resource
Register with:
Route::resource('photos', PhotoController::class);
This generates routes for index, create, store, show, edit, update, destroy.

Q: What is middleware in Laravel?
A: Middleware filters HTTP requests entering your application. It runs before or after a request is handled:
- Authentication — verify user is logged in
- CORS — add cross-origin headers
- Logging — log request details
Defined in app/Http/Middleware/.

Q: How do you create and register custom middleware?
A: Create with Artisan:
php artisan make:middleware CheckAge
Implement logic in the handle() method. Register it in bootstrap/app.php (Laravel 11+) or app/Http/Kernel.php (older versions) as route middleware or global middleware.

Q: What is the difference between global and route middleware?
A: Global middleware runs on every HTTP request to your application (e.g., TrimStrings).
Route middleware is assigned to specific routes or groups:
Route::get('/admin', ...)->middleware('auth');
Route middleware gives you fine-grained control.

Q: What are migrations in Laravel?
A: Migrations are version control for your database. They let you define and modify database schema using PHP code:
php artisan make:migration create_posts_table
Run with php artisan migrate. Roll back with php artisan migrate:rollback.

Q: How do you add a column to an existing table using a migration?
A: Create a new migration:
php artisan make:migration add_email_to_users_table --table=users
In the up() method:
$table->string('email')->after('name');
In down():
$table->dropColumn('email');

Q: What are seeders and factories in Laravel?
A: Seeders populate your database with sample data:
php artisan make:seeder UserSeeder
Factories define blueprints for generating model instances using Faker:
User::factory()->count(50)->create();
Run seeders with php artisan db:seed.

Q: What are some commonly used Artisan CLI commands?
A: - php artisan serve — start dev server
- php artisan migrate — run migrations
- php artisan make:model — create a model
- php artisan tinker — interactive REPL
- php artisan route:list — list all routes
- php artisan cache:clear — clear app cache

Q: How do you create a custom Artisan command?
A: Run:
php artisan make:command SendEmails
This creates a class in app/Console/Commands/. Set the $signature property for the command name and define logic in the handle() method. Run it with:
php artisan mail:send

Q: What is Laravel Tinker?
A: Tinker is an interactive REPL (Read-Eval-Print Loop) powered by PsySH. It lets you interact with your entire Laravel application from the command line:
php artisan tinker
You can create models, run queries, test methods, and dispatch jobs interactively.

Q: What is the Laravel Service Container?
A: The service container is a powerful tool for managing class dependencies and dependency injection. It resolves classes and their dependencies automatically:
$this->app->bind(Interface::class, Implementation::class);
Laravel's core components are all resolved through the container.

Q: What is the difference between bind and singleton in the service container?
A: bind() creates a new instance each time the dependency is resolved.
singleton() resolves the class once and returns the same instance on subsequent calls:
$this->app->singleton(Service::class, function ($app) { return new Service(); });

Q: What is a Service Provider in Laravel?
A: Service providers are the central place for bootstrapping Laravel applications. They register bindings in the service container and configure services:
- register() — bind classes into the container
- boot() — called after all providers are registered; configure routes, event listeners, etc.

Q: What are Facades in Laravel?
A: Facades provide a static-like interface to classes available in the service container:
Cache::get('key');
Behind the scenes, this resolves the cache binding from the container and calls get() on it. They offer concise syntax while remaining testable.

Q: How do real-time Facades work?
A: Any class can be used as a facade by prefixing its namespace with Facades\\:
use Facades\App\Services\PaymentGateway;
PaymentGateway::charge(100);
Laravel dynamically generates a facade for the class, resolving it from the container.

Q: How do you configure and dispatch a queued job in Laravel?
A: Create a job:
php artisan make:job ProcessPodcast
Implement the handle() method. Dispatch it:
ProcessPodcast::dispatch($podcast);
Run the worker:
php artisan queue:work
Configure the driver (Redis, database, SQS) in config/queue.php.

Q: What are queue worker options and retry mechanisms?
A: Key options for php artisan queue:work:
- --tries=3 — max retry attempts
- --timeout=60 — max seconds per job
- --backoff=10 — seconds between retries
Failed jobs go to the failed_jobs table. Retry with php artisan queue:retry all.

Q: What is the difference between queue:work and queue:listen?
A: queue:work boots the framework once and processes jobs efficiently — best for production.
queue:listen restarts the framework for each job — useful during development so code changes take effect immediately, but is slower.

Q: How do you define and listen for events in Laravel?
A: Create an event and listener:
php artisan make:event OrderShipped
php artisan make:listener SendShipmentNotification --event=OrderShipped
Register in EventServiceProvider or use auto-discovery. Dispatch with:
event(new OrderShipped($order));

Q: What are Laravel event subscribers?
A: An event subscriber is a class that subscribes to multiple events from within the class itself:
public function subscribe(Dispatcher $events) {
  $events->listen(OrderShipped::class, [self::class, 'handleShipment']);
}
Register it in the $subscribe property of EventServiceProvider.

Q: How do you send notifications in Laravel?
A: Create a notification:
php artisan make:notification InvoicePaid
Define delivery channels in via() (mail, database, SMS, Slack). Send it:
$user->notify(new InvoicePaid($invoice));
Or use the Notification facade:
Notification::send($users, new InvoicePaid($invoice));

Q: How do you store notifications in the database?
A: Run:
php artisan notifications:table && php artisan migrate
Add 'database' to the via() method and implement toDatabase() or toArray(). Retrieve with:
$user->unreadNotifications;
Mark as read:
$notification->markAsRead();

Q: What are Gates in Laravel authorization?
A: Gates are closure-based authorization checks defined in AuthServiceProvider:
Gate::define('update-post', function (User $user, Post $post) { return $user->id === $post->user_id; });
Check with:
Gate::allows('update-post', $post) or @can('update-post', $post) in Blade.

Q: What are Policies in Laravel and how do they differ from Gates?
A: Policies are classes that organize authorization logic around a model:
php artisan make:policy PostPolicy --model=Post
Methods like update(User $user, Post $post) map to abilities. Policies are better for complex models; Gates are simpler closures for general checks.

Q: How do you authorize actions in a controller?
A: Use the authorize() method:
$this->authorize('update', $post);
This throws an AuthorizationException (403) if denied. You can also use:
- Gate::allows('update', $post)
- $user->can('update', $post)
- @can('update', $post) in Blade

Q: How do you validate form requests in Laravel?
A: Inline validation:
$request->validate(['title' => 'required|max:255', 'body' => 'required']);
Form Request class:
php artisan make:request StorePostRequest
Define rules in the rules() method. Type-hint it in the controller — validation runs automatically.

Q: What are some common Laravel validation rules?
A: - required — field must be present
- string|max:255 — string with max length
- email — valid email format
- unique:users,email — unique in table
- confirmed — matches field_confirmation
- exists:posts,id — must exist in table
- nullable|image|mimes:jpg,png — optional image

Q: How do you create a custom validation rule?
A: Run:
php artisan make:rule Uppercase
Implement the validate() method:
public function validate(string $attribute, mixed $value, Closure $fail): void { if (strtoupper($value) !== $value) { $fail('The :attribute must be uppercase.'); } }
Use it: 'name' => [new Uppercase]

Q: How do you write a basic feature test in Laravel?
A: Create a test:
php artisan make:test UserTest
Use HTTP testing methods:
public function test_homepage_returns_ok(): void { $this->get('/')->assertStatus(200); }
Run with:
php artisan test or ./vendor/bin/phpunit

Q: What is the RefreshDatabase trait used for in testing?
A: use RefreshDatabase; ensures your database is migrated and reset for each test. It wraps each test in a transaction that is rolled back after the test completes, keeping tests isolated without the overhead of re-running migrations every time.

Q: How do you test authenticated routes in Laravel?
A: Use the actingAs() method to simulate an authenticated user:
$user = User::factory()->create();
$this->actingAs($user)->get('/dashboard')->assertStatus(200);
For API tokens, pass the guard:
$this->actingAs($user, 'sanctum');

Q: How do you mock services in Laravel tests?
A: Use Laravel's built-in mocking via the container:
$this->mock(PaymentGateway::class, function ($mock) {
  $mock->shouldReceive('charge')->once()->andReturn(true);
});
Or use Bus::fake(), Event::fake(), Notification::fake() for framework services.

Q: What are Laravel Collections?
A: Collections wrap arrays with a fluent, chainable API for data manipulation:
collect([1, 2, 3])->map(fn($n) => $n * 2)->filter(fn($n) => $n > 2)->values();
Eloquent queries return Collections. They provide 100+ methods like pluck, groupBy, reduce, sortBy, and chunk.

Q: What are some commonly used Collection methods?
A: - map() — transform each item
- filter() — keep items passing a test
- pluck('name') — extract a single column
- groupBy('status') — group by key
- sum('price') — sum a field
- first() / last() — get first/last item
- unique() — remove duplicates

Q: What is the difference between soft deletes and hard deletes in Eloquent?
A: Hard delete removes the record permanently:
$post->delete();
Soft delete sets a deleted_at timestamp instead. Add the trait:
use SoftDeletes;
And add $table->softDeletes(); in the migration. Restore with:
$post->restore();

Q: What are Eloquent scopes?
A: Scopes define reusable query constraints:
Global scope: applies automatically to all queries on a model.
Local scope: applied explicitly:
public function scopeActive($query) { return $query->where('active', true); }
Use as: User::active()->get();

Q: What is Laravel Sanctum used for?
A: Sanctum provides a lightweight authentication system for:
- SPA authentication — cookie-based session auth
- API tokens — simple token-based auth for mobile/third-party apps
Issue tokens with:
$token = $user->createToken('app')->plainTextToken;

Q: What is the difference between firstOrCreate and updateOrCreate in Eloquent?
A: firstOrCreate() inserts a new record only if no matching record is found using the given attributes:
User::firstOrCreate(['email' => $x], ['name' => 'A']);
updateOrCreate() updates the matching record if found, or creates one with both attribute sets merged:
User::updateOrCreate(['email' => $x], ['name' => 'B']);

Q: How do you define a many-to-many relationship in Eloquent?
A: Return belongsToMany from both models pointing at the pivot table:
public function roles() { return $this->belongsToMany(Role::class); }
public function users() { return $this->belongsToMany(User::class); }
Laravel assumes the pivot is role_user (alphabetical, singular). Pass a second argument to override.

Q: How do you attach, detach, and sync records on a many-to-many relationship?
A: $user->roles()->attach($roleId);
$user->roles()->detach($roleId);
$user->roles()->sync([1, 2, 3]);
attach() adds without removing, detach() removes, sync() makes the pivot match exactly the given IDs (removing anything not listed).

Q: How do you access extra columns on a pivot table in a many-to-many relationship?
A: Use withPivot('column1', 'column2') in the relationship definition, then $user->pivot->column1. Add withTimestamps() to auto-populate created_at / updated_at on the pivot.

Q: What is the difference between hasManyThrough and hasOneThrough in Eloquent?
A: Both traverse two relationships via an intermediate model. hasManyThrough returns multiple results (e.g., a country's posts through users). hasOneThrough returns one result (e.g., a user's latest post through comments). The signature is hasManyThrough(Post::class, User::class).

Q: How do you define a polymorphic one-to-many relationship in Eloquent?
A: Use morphMany() on the parent and morphTo() on the child. The child table needs morphs() columns:
$table->morphs('commentable');
Parent: return $this->morphMany(Comment::class, 'commentable');

Q: How do you define a polymorphic many-to-many relationship?
A: Use morphToMany() and morphedByMany(). Both sides need a morphs() column plus a pivot table. Tag example: $post->tags() returns tags, $tag->posts() returns posts via the same pivot.

Q: How do you query a relationship existence with whereHas in Eloquent?
A: whereHas() filters the parent query to rows that have a related record matching a subquery:
User::whereHas('posts', fn($q) => $q->where('published', true))->get();
Use orWhereHas() for OR, and has() when no constraints are needed.

Q: What is the difference between has and whereHas in Eloquent?
A: has('posts') filters to models with at least one related record. whereHas('posts', $cb) additionally accepts a callback to add constraints to the relation query. has() accepts a comparison operator and count: has('posts', '>', 5).

Q: How do you count related models efficiently with withCount in Eloquent?
A: Add a {relation}_count column to the result without loading the relation:
Post::withCount('comments')->orderBy('comments_count', 'desc')->get();
You can pass a callback to filter the count: withCount(['comments as active_comments_count' => fn($q) => $q->where('active', true)]).

Q: What is lazy eager loading and when would you use it?
A: Lazy eager loading resolves N+1 after the parent query already ran, via load():
$posts = Post::all();
$posts->load('author', 'comments');
Use it when you already have a collection and need related models only conditionally (e.g., inside a Blade loop or when gated by logic).

Q: How do you prevent lazy loading during development in Laravel?
A: Call Model::preventLazyLoading(!app()->isProduction()); in a service provider (often AppServiceProvider::boot()). Eloquent then throws LazyLoadingViolationException on any unguarded lazy relation access in non-production environments.

Q: What is the difference between find, findOrFail, and firstOrFail in Eloquent?
A: User::find(1);              // null if missing
User::findOrFail(1);       // throws ModelNotFoundException
User::where('active', 1)->firstOrFail();
Use findOrFail / firstOrFail when the record must exist — Laravel converts the exception into an automatic 404 HTTP response.

Q: How do you insert, update, and delete records using Eloquent?
A: $model = new User; $model->name = 'A'; $model->save();
User::create(['name' => 'A']);              // requires $fillable or $guarded
$user->update(['name' => 'B']);
$user->delete();
Mass assignment via create() / update() is gated by $fillable or unguarded via $guarded = [].

Q: What is the purpose of the $fillable and $guarded properties in Eloquent models?
A: Both protect against mass-assignment vulnerabilities. $fillable whitelists attributes allowed in create()/update():
protected $fillable = ['name', 'email'];
$guarded blacklists attributes, with $guarded = ['*'] blocking all mass assignment except the primary key.

Q: How do you define a one-to-one relationship in Eloquent?
A: Use hasOne() on the parent and belongsTo() on the child. Convention: the child table contains the foreign key (user_id for a Phone). Example:
return $this->hasOne(Phone::class);

Q: How do you customize the foreign key or local key in an Eloquent relationship?
A: Pass extra arguments:
return $this->hasOne(Phone::class, 'owner_id', 'id');
Second arg = foreign key on related table, third arg = local key on parent table. Same pattern works for belongsTo, hasMany, etc.

Q: How do you retrieve records matching specific criteria using whereIn and whereBetween?
A: User::whereIn('id', [1, 2, 3])->get();
User::whereBetween('age', [18, 30])->get();
User::whereNotIn('status', ['banned'])->get();
Combine with orWhereIn / whereNull / whereDate for richer filters.

Q: How do you order and limit query results in Eloquent?
A: User::orderBy('created_at', 'desc')->get();
User::latest()->get();                  // order by created_at desc
User::oldest()->get();
User::inRandomOrder()->first();
User::skip(10)->take(5)->get();
latest / oldest accept an optional column name.

Q: How do you retrieve only specific columns with Eloquent?
A: Use select:
User::select('id', 'name')->get();
Or pluck a single column:
User::pluck('email');
Use addSelect when adding to an existing select in a subquery.

Q: How do you use chunk and chunkById to process large Eloquent result sets?
A: User::chunk(200, function ($users) {
  foreach ($users as $u) { /* ... */ }
});
chunkById paginates by primary key and is safer when records are modified mid-iteration (avoids skipped rows). lazy() and lazyById() return a LazyCollection for stream-style processing.

Q: How do you use cursor to iterate over a large Eloquent result set?
A: User::cursor() runs a single unbuffered DB query and yields models one at a time using PHP generators. Memory stays flat regardless of result size, ideal for exports. Use cursorPaginate when you also need pagination metadata.

Q: How do you write a raw SQL expression in Eloquent safely?
A: Use DB::raw() for select fragments and parameterize user input:
User::select(DB::raw('count(*) as total, year(created_at) as yr'))->groupBy('yr')->get();
Never concatenate user input into raw SQL — always bind: ->whereRaw('email = ?', [$email]).

Q: How do you detect changes on an Eloquent model after updating it?
A: Use $user->isDirty('email'), $user->isClean(), $user->wasChanged() (after save), and $user->getOriginal('email') to read the pre-update value. isDirty() checks pending changes; wasChanged() checks what was actually saved.

Q: How do you use the booted method in an Eloquent model for global setup?
A: protected static function booted(): void {
  static::creating(fn ($m) => $m->uuid = Str::uuid());
  static::addGlobalScope(new ActiveScope);
}
booted() is the canonical place to register model events (creating, created, updating, saving, deleted, etc.) and global scopes.

Q: How do you create a global scope and apply it automatically to a model?
A: class ActiveScope implements Scope {
  public function apply(Builder $b, Model $m) {
    return $b->where('active', true);
  }
}
Register via static::addGlobalScope(new ActiveScope) in booted(). Remove with Model::withoutGlobalScope(ActiveScope::class).

Q: How do you temporarily disable all global scopes on an Eloquent query?
A: Call withoutGlobalScopes():
User::withoutGlobalScopes()->get();
To remove specific scopes: withoutGlobalScope(ActiveScope::class) or withoutGlobalScopes([ScopeA::class, ScopeB::class]).

Q: How do you cast attributes to specific data types in Eloquent?
A: Use the $casts property:
protected $casts = [
  'is_admin' => 'boolean',
  'settings' => 'array',
  'published_at' => 'datetime',
  'price' => 'decimal:2',
];
Casts also support custom cast classes via AsEnum::class or AsCollection::class in Laravel 11+.

Q: How do you cast an attribute to a PHP enum in Eloquent?
A: Define the enum (enum Status: string { case Active = 'active'; case Inactive = 'inactive'; }), then in the model:
use Illuminate\Database\Eloquent\Casts\AsEnum;
protected $casts = ['status' => AsEnum::class.':'.Status::class];
Reading returns the enum; assigning an enum or scalar back works either way.

Q: How do you implement an Eloquent observer and what events can it listen to?
A: Generate with php artisan make:observer UserObserver --model=User, then register in a provider:
User::observe(UserObserver::class);
Events: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored.

Q: What is the difference between the saving and creating events in Eloquent?
A: saving fires before any insert or update (also updating). creating fires only before inserts (companion: updating). After events are created / updated / saved. saved is fired on both insert and update and is the safest hook for side effects.

Q: How do you prevent model events from firing temporarily?
A: Use Model::withoutEvents(function () { /* mass operations */ });, or call $model->saveQuietly() / deleteQuietly() / updateQuietly() to skip events for a single save. Model::unsetEventDispatcher() removes the dispatcher entirely.

Q: How do you generate UUIDs automatically for an Eloquent model?
A: public function newUniqueId() { return (string) Str::uuid(); }
public $incrementing = false;
protected $keyType = 'string';
Or set in creating: static::creating(fn ($m) => $m->{$m->getKeyName()} = Str::uuid());. The migration should use $table->uuid('id')->primary();.

Q: How do you implement repository-pattern style query encapsulation with Eloquent's query scopes?
A: Use a local scope that returns the builder, optionally accepting parameters:
public function scopeOfType(Builder $q, string $type) { return $q->where('type', $type); }
Then chain: Post::ofType('news')->published()->get();. Combine with Scope classes for complex reusable logic.

Q: What is the difference between fresh and refresh on an Eloquent model?
A: $copy = $model->fresh();        // new instance from DB
$model->refresh();              // mutates the same instance
fresh() leaves the original untouched; refresh() overwrites attributes (and relations by default) on the existing object. Use refresh(['comments']) to also reload specific relations.

Q: How do you replicate an Eloquent model (create a copy not yet saved)?
A: Call $new = $model->replicate(); to get a new unsaved instance with attributes copied. Optionally exclude attributes:
$new = $model->replicate(['views_count']);
Then modify and $new->save();. The new record gets a fresh primary key and timestamps.

Q: How do you chunk the result of an Eloquent query inside a job for queue safety?
A: Combine chunkById with Bus::batch:
Post::chunkById(500, function ($posts) {
  Bus::batch($posts->map(fn ($p) => new ProcessPost($p)))->dispatch();
});
This keeps memory bounded and parallelizes work safely.

Q: How do you define a route group with shared prefix and middleware?
A: Route::prefix('admin')->middleware('auth')->group(function () {
  Route::get('/dashboard', ...);
  Route::resource('posts', AdminPostController::class);
});
Other group attributes: name (prefixes route names), domain (subdomain), where (regex constraints), scopeBindings() (nested binding resolution).

Q: What is the difference between Route::get and Route::post and the other HTTP verbs?
A: HTTP verbs map to controller actions: Route::get() (read), Route::post() (create), Route::put() / Route::patch() (update), Route::delete() (delete), Route::any() (all), Route::match(['get','post'], ...) (subset). Use Route::resource() to declare all CRUD verbs at once.

Q: How do you constrain a route parameter to a regex pattern?
A: Use where() on the route definition:
Route::get('/user/{name}', ...)->where('name', '[A-Za-z]+');
For multiple: ->where(['id' => '[0-9]+', 'name' => '[a-z]+']). Global patterns go in Route::pattern('id', '[0-9]+') inside a service provider.

Q: What is the difference between implicit and explicit route model binding?
A: Implicit binding infers the model from the type-hinted parameter:
function show(Post $post)
Explicit binding lets you customize resolution:
Route::bind('post', fn($v) => Post::where('slug', $v)->firstOrFail());
Implicit covers 90% of cases; explicit is for slugs, soft-deletes, multi-tenant scoping, etc.

Q: How do you customize the resolution logic for a specific Eloquent model in route binding?
A: Override resolveRouteBinding($value, $field = null) on the model:
public function resolveRouteBinding($value, $field = null) {
  return $this->where('slug', $value)->firstOrFail();
}
This lets every route using the model resolve by slug without explicit binding.

Q: How do you scope route model binding to a parent resource?
A: Use Route::scopeBindings() or nested route definitions so child binding queries include the parent:
Route::scopeBindings()->group(function () {
  Route::get('/users/{user}/posts/{post}', ...);
});
Define Post::resolveRouteBindingQueryUsing(fn($q, $v, $f) => $q->whereBelongsTo($user)) on the child model (Laravel 11+) for the canonical way.

Q: How do you enable automatic scoping of route model bindings by parent?
A: In Laravel 11+, override the model's binding query:
Post::resolveRouteBindingQueryUsing(fn($q, $value, $field) => $q->whereBelongsTo(request()->user()));
Or define a relationship like posts() on the parent and use scoped routes:
Route::get('/users/{user}/posts/{post}', [PostController::class, 'show']);

Q: How do you generate URLs for controller actions and named routes?
A: route('users.show', ['id' => 1]);                  // named route
action([UserController::class, 'show'], ['id' => 1]);
URL::signedRoute('orders.download', ['order' => 5]);
route() resolves named routes; pass array params or a model (auto-extracts its primary key and route key).

Q: What are signed URLs in Laravel and how do you generate them?
A: Signed URLs include a hash that Laravel validates to prevent tampering. Generate:
URL::temporarySignedRoute(
  'unsubscribe', now()->addMinutes(30), ['user' => 1]
);
Validate with the signed middleware on the route.

Q: How do you rate limit incoming requests with the throttle middleware?
A: Route::middleware('throttle:60,1')->group(...);
RateLimiter::for('api', fn ($r) =>
  Limit::perMinute(60)->by($r->user()?->id ?: $r->ip()));
Register named limiters in a service provider's boot() using RateLimiter::for(...), then use throttle:api.

Q: How do you create an API resource route that excludes the create and edit actions?
A: Use except:
Route::resource('posts', PostController::class)->except(['create', 'edit']);
Or use apiResource() which already excludes them since API clients don't need forms:
Route::apiResource('posts', PostController::class);

Q: How do you add additional routes to a resource controller without breaking RESTful verbs?
A: Use Route::resource() plus explicit routes before it (more specific routes win):
Route::get('/posts/popular', [PostController::class, 'popular']);
Route::resource('posts', PostController::class);
This keeps the standard CRUD routes while exposing custom actions.

Q: How do you pass middleware parameters in Laravel?
A: Append them after a colon:
Route::get('/admin', ...)->middleware('role:editor,admin');
In the middleware:
public function handle($request, Closure $next, ...$roles) { ... }
Each comma-separated value becomes a variadic argument.

Q: How do you terminate a middleware after the response has been sent?
A: Implement terminate($request, $response) on the middleware class. Laravel calls it after sending the response. Don't put critical security logic here — the response is already on the wire.

Q: How do you share a variable with all Blade views globally?
A: Use View::share('key', $value) in a service provider's boot(), or return data from AppServiceProvider::boot():
view()->share('siteName', config('app.name'));
The variable is then available in every template rendered afterwards.

Q: How do you register a custom Blade directive?
A: In a service provider:
Blade::directive('datetime', fn ($exp) => "format('Y-m-d'); ?>");
Use it: @datetime($post->created_at). Return PHP to execute. Use Blade::if('admin', fn() => auth()->check() && auth()->user()->isAdmin()) for conditional directives.

Q: How do you render markdown or a JSON view in Blade?
A: Use the @markdown directive or Str::markdown():
@markdown($post->body)
For raw JSON in a <script> tag: @json($data) (HTML-escaped and valid JSON).

Q: How do you render a Blade view from a string instead of a file?
A: Use Blade::render('Hello, {{ $name }}', ['name' => 'A']) (Laravel 9+) or the older view::render(). Useful for emails, dynamic templates, or stored HTML snippets.

Q: How do you create an anonymous Blade component?
A: Drop a file into resources/views/components/. For resources/views/components/alert.blade.php, use it as <x-alert />. No class needed. Slots work with {{ $slot }}; named slots with <x-slot:name>...</x-slot:name>.

Q: How do you stack and push scripts/styles from child Blade templates?
A: @stack('scripts')
@push('scripts')
  <script src="/x.js"></script>
@endpush
The parent uses @stack('scripts') to render, child templates @push content into the stack. @prepend adds to the beginning.

Q: How do you conditionally include a partial in Blade?
A: Use @includeWhen($condition, 'partial.name', ['data' => $x]) or @includeIf('partial.name', [...]) to silently skip when the view is missing. @includeFirst(['admin.post', 'post'], [...]) tries each in order.

Q: How do you use the @each directive to render a collection of partials?
A: @each('partials.item', $items, 'item', 'partials.empty')
Renders partials.item for each $items, exposing each as $item. The 4th argument is the view to render when the collection is empty.

Q: What does @csrf do in Blade and why is it required?
A: @csrf outputs a hidden _token input used by Laravel's VerifyCsrfToken middleware to validate that POST/PUT/PATCH/DELETE requests originated from your site, preventing cross-site request forgery. It must be inside any HTML <form> that uses a non-GET verb.

Q: How do you handle CSRF token mismatches in SPAs that POST to the same Laravel app?
A: For SPA auth via Sanctum, send the XSRF-TOKEN cookie value in the X-XSRF-TOKEN header. Axios does this automatically when withCredentials is set. Configure in config/sanctum.php under stateful.

Q: How do you render pagination links in Blade?
A: In a controller: $posts = Post::paginate(15); In the view:
{{ $posts->links() }}
This renders the default Tailwind-styled pager. Use simplePaginate() for next/prev only, or pass a custom view: ->links('vendor.pagination.custom').

Q: How do you customize the pagination URL query string name?
A: The paginator's page query parameter is the default. Change globally in AppServiceProvider::boot():
Paginator::defaultSimpleView('pagination::simple-default');
Or per-call: Paginator::currentPageResolver(fn() => request('p', 1)).

Q: How do you implement cursor pagination in Eloquent?
A: Post::orderBy('id')->cursorPaginate(15);
Renders cursor query strings instead of page numbers — faster on large datasets and stable across inserts. Use ->previousCursor() and ->nextCursor() on the paginator instance.

Q: How do you customize the default pagination view per call?
A: Pass it to links():
{{ $items->links('pagination::tailwind') }}
Or build your own view and reference it: $items->links('partials.pager'). The view receives a Paginator instance.

Q: What is the difference between paginate and simplePaginate?
A: paginate() runs a COUNT(*) query and exposes the total record count for "showing X of Y" UIs. simplePaginate() only knows whether a next page exists (one extra query). simplePaginate is cheaper and preferred for very large tables.

Q: How do you run a query inside a database transaction in Laravel?
A: DB::transaction(function () {
  Account::find(1)->decrement('balance', 100);
  Account::find(2)->increment('balance', 100);
});
On any exception, all DB changes roll back automatically. Pass a second argument for retry attempts: DB::transaction($cb, 5).

Q: How do you manually manage a database transaction?
A: DB::beginTransaction();
try { /* ... */ DB::commit(); }
catch (\Throwable $e) { DB::rollBack(); throw $e; }
Use DB::afterCommit(fn() => ...) to defer logic until the outermost transaction commits — useful for queue dispatch or notifications inside a transaction.

Q: What is a database deadlock and how does Laravel handle retry-on-deadlock?
A: A deadlock occurs when two transactions wait on each other's locks. Use DB::transaction($cb, $attempts) — Laravel retries the closure on serialization failures (Laravel detects deadlocks and rethrows; the $attempts parameter is the retry count). Combine with idempotent operations.

Q: How do you configure multiple database connections in Laravel?
A: In config/database.php define entries under 'connections'. Use them via:
DB::connection('pgsql')->table(...)->get();
Or set a model's $connection property. Use a read/write split: 'mysql' => ['read' => [...], 'write' => [...]].

Q: How do you listen for query events during development?
A: Enable in AppServiceProvider:
DB::listen(fn ($q) => logger()->info($q->sql, $q->bindings, $q->time));
Or use DB::enableQueryLog() + DB::getQueryLog(). The Laravel Debugbar package wraps this for a UI.

Q: How do you write a migration that creates a foreign key constraint?
A: Schema::create('posts', function (Blueprint $t) {
  $t->id();
  $t->foreignId('user_id')->constrained()->cascadeOnDelete();
  $t->string('title');
});
constrained() infers the table name from the column; pass an argument to override (constrained('users')). Use cascadeOnUpdate(), nullOnDelete(), or restrictOnDelete().

Q: How do you add a composite or compound unique index via a migration?
A: $table->unique(['user_id', 'slot']);   // composite unique
$table->index(['status', 'created_at']);   // composite non-unique
Composite indexes speed up queries filtering or sorting by their leftmost columns. Drop with $table->dropUnique(['user_id', 'slot']).

Q: How do you drop a column or rename a column safely in a migration?
A: $table->dropColumn('is_admin');
$table->dropColumn(['a', 'b']);
$table->renameColumn('old', 'new');
Renaming a column requires the doctrine/dbal package on Laravel < 10. From Laravel 10+ native column renames work without extra dependencies.

Q: How do you create a migration that uses raw SQL statements?
A: Use DB::statement():
DB::statement('ALTER TABLE posts ADD FULLTEXT(title, body)');
For rolling back: DB::statement('ALTER TABLE posts DROP INDEX title_body_fulltext') in down().

Q: What is the difference between truncate and delete in migrations?
A: Schema::table('x', fn (Blueprint $t) => $t) + DB::table('x')->truncate() removes all rows and resets auto-increment. DB::table('x')->delete() removes rows but does not reset the sequence. Truncate is faster but cannot be rolled back inside a transaction in MySQL.

Q: How do you define a Factory state in Laravel?
A: public function suspended(): static {
  return $this->state(['suspended_at' => now()]);
}
Use: User::factory()->suspended()->create(); Chain multiple states: User::factory()->admin()->suspended()->create();.

Q: How do you define a Factory relationship in Laravel?
A: public function definition(): array {
  return ['user_id' => User::factory(), 'title' => fake()->sentence()];
}
Passing a factory as a value automatically creates and links a parent. Use User::factory()->for(Post::factory())->create() to make the reverse: a post belonging to a user.

Q: How do you seed the database with a Seeder and which command runs all seeders?
A: Create: php artisan make:seeder PostSeeder. Define inserts in run(). Call other seeders: $this->call([UserSeeder::class, PostSeeder::class]). Run all from DatabaseSeeder via:
php artisan db:seed
Or migrate + seed in one step: php artisan migrate --seed.

Q: What is the difference between migrate:fresh and migrate:refresh?
A: migrate:refresh rolls back all migrations then re-runs them (keeps tables). migrate:fresh drops all tables then re-runs (destroys data). Use --seed with either:
php artisan migrate:fresh --seed
Use fresh when schema is broken; refresh when you want to undo and reapply.

Q: How do you create a single-file Artisan command with a closure signature?
A: In Laravel 11+, register in routes/console.php:
Artisan::command('mail:send {user}', function ($user) {
  Mail::to($user)->send(new OrderShipped);
})->purpose('Send a marketing email')->hourly();
Closure commands support arguments, options, scheduling, and isolation.

Q: How do you schedule an Artisan command to run every minute in production?
A: Register the schedule in routes/console.php (Laravel 11+) or App\Console\Kernel:
Schedule::command('emails:send')->everyMinute()->withoutOverlapping();
Then add * * * * * cd /path && php artisan schedule:run >> /dev/null 2>&1 to crontab.

Q: What is withoutOverlapping used for in scheduled tasks?
A: withoutOverlapping() prevents a scheduled task from running concurrently with itself — useful for long-running jobs. It writes a mutex file and respects a expireAt:
Schedule::command('x')->withoutOverlapping(15)->runInBackground();

Q: How do you run a scheduled command on a specific timezone?
A: Use ->timezone('America/New_York'):
Schedule::command('reports:daily')->dailyAt('09:00')->timezone('Europe/Zagreb');
Laravel evaluates the cron in that timezone; the underlying cron daemon still runs on UTC.

Q: How do you prevent a scheduled task from running when a condition is met?
A: Chain ->when() or ->skip():
Schedule::command('emails:blast')->when(fn () => ! app()->isDownForMaintenance())->daily();
->skip(fn () => ...) is the inverse. ->environments('production') restricts by APP_ENV.

Q: How do you implement custom cache logic with the Cache helper and Cache facade?
A: Cache::put('key', $value, now()->addMinutes(10));
Cache::remember('users', 60, fn () => User::all());
Cache::increment('hits');
Cache::forget('key');
Cache::flush();
Backend is configured in config/cache.php — file, redis, database, memcached, or array (testing).

Q: What is the difference between Cache::remember and Cache::rememberForever?
A: remember($key, $ttl, $cb) caches the closure result for $ttl seconds. rememberForever($key, $cb) caches until you call Cache::forget($key). Use rememberForever for data that rarely changes; forget it explicitly when you mutate the source.

Q: How do you atomically read or write a value to the cache using a lock?
A: Use Cache::lock('key', 10):
Cache::lock('foo')->block(5, function () { /* exclusive */ });
block() waits up to N seconds for the lock. get(fn) runs the callback if the lock is acquired, else returns null.

Q: How do you tag cache entries and clear them by tag?
A: Use a cache store that supports tags (Redis, Memcached):
Cache::tags(['users'])->put('user:1', $user, 600);
Cache::tags(['users'])->flush();
File and database drivers do not support tags. flush() evicts every entry with the tag.

Q: How do you configure the default cache store at runtime?
A: In .env: CACHE_STORE=redis. Or per-call:
Cache::store('redis')->put('k', 'v', 60);
Custom stores can be added with Cache::extend('myStore', fn() => ...) in a service provider.

Q: How do you send a plain-text or HTML email in Laravel?
A: Use Mail with raw text:
Mail::raw('Hello!', function ($m) {
  $m->to('a@b.com')->subject('Hi');
});
Or send a Markdown/HTML view:
Mail::send('emails.welcome', ['user' => $u], function ($m) use ($u) { $m->to($u->email); });

Q: How do you create a Mailable class for reusable emails?
A: Generate: php artisan make:mail OrderShipped. Set envelope, content, attachments:
public function envelope(): Envelope { return new Envelope(subject: 'Shipped'); }
public function content(): Content { return new Content(markdown: 'mail.shipped'); }
Send: Mail::to($u)->send(new OrderShipped($order)).

Q: How do you make a Mailable queueable so emails are sent asynchronously?
A: Implement ShouldQueue:
class OrderShipped extends Mailable implements ShouldQueue
Set public $tries = 3; and public $backoff = 60;. Mail::send() dispatches the job onto the queue worker instead of sending inline.

Q: How do you render Markdown emails with predefined templates?
A: Use Content::markdown('mail.order') and place the view in resources/views/mail/order.blade.php. You can use Blade components like @component('mail::button', ['url' => $url]) from resources/views/vendor/mail/html/ for a styled layout.

Q: How do you customize the Markdown mail default theme?
A: Publish: php artisan vendor:publish --tag=laravel-mail
This copies resources/views/vendor/mail/. Edit html/themes/default.css or create a new theme and reference it:
public function content(): Content { return new Content(markdown: 'mail.x')->theme('my-theme'); }

Q: How do you attach files or raw data to a Mailable?
A: public function attachments(): array {
  return [Attachment::fromStorageDisk('s3', 'invoice.pdf')->as('Inv.pdf')];
}
For inline images: embed($path) in the build closure. fromPath / fromData accept raw strings.

Q: How do you use the Storage facade to read, write, and delete files?
A: Storage::disk('public')->put('a.txt', 'contents');
Storage::disk('public')->get('a.txt');
Storage::disk('public')->exists('a.txt');
Storage::disk('public')->delete('a.txt');
Storage::disk('public')->files('images');
Disks: local, public, s3, ftp, sftp. Default disk is config/filesystems.php 'default'.

Q: How do you make uploaded files publicly accessible?
A: Run php artisan storage:link to symlink storage/app/public into public/storage. Save to the public disk: $request->file('avatar')->store('avatars', 'public'). Serve via asset('storage/avatars/x.jpg').

Q: How do you validate an uploaded file is an image under 2 MB?
A: In a Form Request:
'photo' => ['required', 'image', 'max:2048']
Or manually:
$request->validate(['photo' => 'file|mimes:jpg,png|max:2048']);
Access the file with $request->file('photo'); move with ->store('images') or ->move(public_path(), 'x.jpg').

Q: How do you call an external HTTP API using Laravel's HTTP client?
A: $response = Http::get('https://api.example.com/users');
return $response->json();
$response->throw();              // throws on 4xx/5xx
Http::timeout(5)->retry(3)->get(...);
Set a base URL: Http::baseUrl('https://api.x.com')->withToken($t). POST JSON: Http::post($url, $data).

Q: How do you test HTTP client calls without hitting the real API?
A: Use Http::fake():
Http::fake(['api.example.com/*' => Http::response(['ok' => true], 200)]);
After the call, assert: Http::assertSent(fn ($req) => $req['url'] === '...'). Combine with Http::preventStrayRequests() to catch unwired calls.

Q: How do you broadcast an event over WebSockets in Laravel?
A: Implement ShouldBroadcast on the event:
public function broadcastOn() { return new Channel('orders'); }
Trigger: event(new OrderShipped($order)). Frontends (Echo) listen via Echo.channel('orders').listen('OrderShipped', ...). Use PrivateChannel / PresenceChannel for auth.

Q: How do you authorize a private broadcast channel?
A: Define a route in routes/channels.php:
Broadcast::channel('orders.{id}', fn ($user, $id) => $user->id === (int) $id);
Private channels use the auth:api middleware. PresenceChannel callbacks additionally return an array of presence data.

Q: How do you write data to the session in Laravel?
A: session(['key' => 'value']);
session()->put('key', 'value');
request()->session()->flash('status', 'Saved');
$value = session('key', 'default');
Drivers: file, cookie, database, redis, array. Configured in config/session.php.

Q: How do you implement flash data that lives for only the next request?
A: Use flash():
$request->session()->flash('status', 'Profile updated!');
Retrieve with session('status'). now() is a fluent alternative: session()->now('info', 'Just for this request'). keep() re-flashes for an additional request.

Q: How do you regenerate the session ID and prevent session fixation?
A: Call $request->session()->regenerate(); after login or privilege changes. It writes a new ID and migrates data. Combine with ->invalidate() to drop all session data on logout.

Q: How do you read the current authenticated user in Laravel?
A: Use the auth() helper or Auth facade:
$user = auth()->user();
Auth::user();
Auth::id();
Auth::check();             // bool
Auth::guest();
For specific guards: Auth::guard('api')->user().

Q: How do you log a user in programmatically (without the login form)?
A: Auth::login($user);
Auth::loginUsingId(5);
Auth::attempt(['email' => $email, 'password' => $pw], $remember = true);
attempt() verifies credentials and starts the session. Pass true as the second arg to issue a "remember me" cookie.

Q: How do you implement remember-me (persistent login) cookies?
A: In Auth::attempt($credentials, true), the true flag issues a long-lived cookie. Add Illuminate\Cookie\Middleware\EncryptCookies middleware (already on by default). Implement Auth::viaRemember() check on subsequent requests.

Q: How do you retrieve a value from configuration files in Laravel?
A: Use the config() helper:
config('app.timezone');
config(['app.timezone' => 'UTC']);
Always access through config() — never env() outside config files. php artisan config:cache compiles all config into one file in production.

Q: Why should env() never be called outside config files?
A: Once config:cache runs, all env() calls outside config return null because .env is no longer loaded per request. This causes silent failures in production. Inside config files is the only safe place; everywhere else use config().

Q: How do you log messages to a channel in Laravel?
A: Log::info('User signed in', ['id' => $u->id]);
Log::channel('slack')->error('Boom');
Log::stack(['single', 'slack'])->warning('Heads up');
Channels configured in config/logging.php: single, daily, errorlog, syslog, slack, monolog, custom.

Q: How do you use Laravel Pint or PHP_CodeSniffer to lint code?
A: Pint (Laravel's default, zero-config): vendor/bin/pint. Auto-fix unsafe rules: vendor/bin/pint --test reports without fixing. Pint config goes in pint.json at the project root. PHPCS: vendor/bin/phpcs --standard=PSR12 app/

Q: How do you handle file uploads in a Laravel controller?
A: $path = $request->file('avatar')->store('avatars', 'public');
$path = $request->file('avatar')->storeAs('avatars', 'me.jpg', 'public');
Then store the returned path on the model. Use ->getClientOriginalName(), ->extension(), ->size(), ->isValid() for validation.

Q: How do you handle a 404 / ModelNotFoundException globally?
A: Render a custom view: implement App\Exceptions\Handler::render() or simply throw abort(404). In Laravel 11+: bootstrap/app.php uses withExceptions(fn ($e) => $e->render(fn (ModelNotFoundException $e, $r) => ...)). Convert to a JSON response when $request->wantsJson().

Q: How do you return a JSON response with custom HTTP status in Laravel?
A: return response()->json(['error' => '...'], 422);
return response()->noContent();                   // 204
return response()->redirectTo('/foo', 301);
From a resource route, throw abort(response()->json(...), 422) for in-controller error handling.

Q: How do you write a custom 404 / 500 error page?
A: Create resources/views/errors/404.blade.php and resources/views/errors/500.blade.php. Laravel renders them automatically when an HTTP exception occurs. Use $exception->getStatusCode() inside if needed.

Q: How do you scope query builder results with the DB facade?
A: DB::table('users')->where('active', true)->orderBy('id')->get();
DB::table('users')->insert(['name' => 'A']);
DB::table('users')->where('id', 1)->update(['name' => 'B']);
DB::table('users')->where('id', 1)->delete();
DB::table('users')->truncate();
DB returns stdClass arrays; first() returns one row or null.

Q: How do you write a UNION or subquery in the query builder?
A: $q = DB::table('a')->select('id', 'name');
DB::table('b')->union($q)->get();
DB::table('users')->select('*')->addSelect(['post_count' =>
  DB::table('posts')->selectRaw('count(*)')->whereColumn('posts.user_id', 'users.id')
])->get();
Subqueries become a select column; the result still has users.*.

Q: How do you use the firstWhere helper in Eloquent or the query builder?
A: User::firstWhere('email', 'a@b.com') is shorthand for where(...)->first(). Variants: whereKey(5) / whereKeyNot(5) match by primary key; whereKey([1,2,3]) matches any of them.