← BackLaravel30 Q

Laravel

30 questions | entry to principal | answers written to be said out loud, not read

entry

What is a service provider?

A service provider is where Laravel bootstraps things. It has a register method for binding things into the container and a boot method for code that should run once everything is registered, like defining routes, view composers, or event listeners. Every core Laravel feature, and every package, gets wired up through a provider.

What is route model binding?

Instead of manually looking up a model by an id in the controller, I type-hint the model in the route signature and Laravel resolves it for me based on the route parameter. If no matching record exists it throws a 404 automatically. I can also bind on a different column, like a slug, by overriding getRouteKeyName on the model.

What is Blade and why not just use plain PHP templates?

Blade is Laravel's templating engine. It compiles down to plain PHP, so there's no real runtime overhead, but it gives me cleaner syntax for things like conditionals, loops, layouts, and component includes. I like that {{ }} escapes output by default, which protects against XSS unless I deliberately opt out with the raw {!! !!} echo syntax.

What is an Eloquent model?

An Eloquent model is the active record representation of a database table, so each instance maps to a row and the class itself represents the table. I use it to query, create, and update data with an expressive API instead of writing raw SQL everywhere. I also guard against mass assignment by explicitly listing fillable or guarded attributes, so a stray input field can't overwrite something like an is_admin column.

What's the difference between migrations, seeders, and factories?

Migrations are version control for the database schema, so every environment ends up with the exact same tables and columns, and I can roll one back if it turns out to be wrong. Seeders populate the database with data I want to exist, like default roles or an admin user. Factories generate fake data for testing and local development, and I usually combine the two, calling a factory from a seeder to fill the database with realistic sample records.

How does Laravel's task scheduler work?

Instead of managing a pile of individual cron entries on the server, I define all my recurring tasks in one schedule, like a command that runs daily or a job that runs every 5 minutes. The only cron entry the server actually needs is one that runs php artisan schedule:run every minute, and Laravel figures out what's actually due to run.

junior

Walk me through what happens when a request hits a Laravel app.

A request comes in through public/index.php, which boots the framework and hands the request to the HTTP kernel. The kernel runs the request through global middleware and route middleware, then the router matches it to a controller or closure. Laravel resolves that controller's dependencies out of the container, runs the action, and the response travels back out through the middleware stack before it's sent to the browser.

How does dependency injection actually work in a Laravel controller?

I type-hint the class or interface I need in the constructor or method signature, and Laravel's container inspects that signature and resolves each dependency automatically, including nested dependencies. For route model binding, Laravel goes further and resolves the actual model instance from the route parameter. I never call new directly on a service I want the container to manage.

What is middleware and how would you write one?

Middleware sits between the request coming in and the response going out, so it's the natural place for cross-cutting concerns like authentication, logging, or CORS. Each middleware gets the request and a next closure, decides whether to act before calling next, after, or both, and can short-circuit the request entirely by returning its own response.

Why use a form request instead of validating in the controller?

A form request pulls validation and authorization out of the controller into its own class, which keeps the controller focused on the actual action. It has a rules method for the validation rules and an authorize method to decide whether the user is even allowed to make this request. If validation fails, Laravel automatically redirects back with errors or returns a 422 for an API call.

Explain hasMany, belongsTo, and belongsToMany.

hasMany and belongsTo describe a one-to-many relationship from either side, like a User hasMany Posts, and a Post belongsTo a User. belongsToMany is for a many-to-many relationship, like Users and Roles, and it goes through a pivot table that stores the pairs. Once those relationships are defined as methods on the model, I can call them like properties and Eloquent handles the underlying joins.

What is a polymorphic relationship?

A polymorphic relationship lets one model belong to more than one other model type through a single association, like Comments that can belong to either a Post or a Video. Laravel stores a type column alongside the foreign key so it knows which table to look up. I reach for it when I'd otherwise be duplicating the same relationship across several models.

What are query scopes in Eloquent?

A scope is a reusable piece of a query defined as a method on the model, prefixed with scope, that I can chain onto queries. Local scopes are opt-in and chainable, like calling published then latest on the Post model, while a global scope applies automatically to every query for that model, like Laravel's own soft delete scope. I use scopes to keep common query logic in one place instead of copying where clauses everywhere.

What are accessors and casts used for?

An accessor lets me transform an attribute whenever I read it off the model, without changing what's actually stored in the database, like formatting a name or computing a full URL. A cast handles the type conversion automatically, so a database column stored as a string or integer comes back as a proper PHP type like a DateTime, a boolean, or an array from JSON. Both keep that transformation logic in the model instead of scattered across the app.

How do you handle database transactions in Laravel?

I wrap the operations in DB::transaction with a closure, and Laravel commits everything if the closure finishes successfully or rolls back the whole thing if any exception is thrown. I use this whenever multiple writes need to succeed or fail together, like creating an order and decrementing inventory, so I never end up with half-applied changes.

How do notifications differ from just sending mail directly?

A notification is a single class that can go out over multiple channels, like mail, database, Slack, or SMS, without duplicating the logic for each one. If I just call the Mail facade directly, I've hardcoded myself to email only. Notifications also give me a database channel out of the box, which is what most in-app notification bells are built on.

What's the difference between a policy and a gate?

A gate is a simple closure-based authorization check, good for something that isn't tied to a specific model, like whether a user can access the admin panel. A policy is a class organized around a single model, with methods like update or delete that map to the actions on that model, and Laravel automatically resolves the right policy when I call can on the user with the model instance.

What are API resources and why not just return the model?

An API resource controls exactly what shape gets serialized to JSON, so I'm not accidentally exposing every column on the model, including things like a password hash or internal flags. It also gives me one place to rename fields, format dates, and include relationships conditionally, so the response is consistent no matter which controller returns it.

senior

What is a facade, really?

A facade like Cache or Route looks like a static call, but under the hood it's a static proxy that resolves the real object out of the container and forwards the call to it. So Cache::get('key') is really pulling the cache manager instance out of the container and calling get on it. That means facades are still testable, since I can swap what's bound in the container or use the built-in fake helpers.

When would you reach for a single-action controller or an action class instead of a normal resource controller?

When a controller has one clear job that doesn't fit neatly into index, store, update, and destroy, I'll use a single-action controller with an __invoke method, or pull the logic into a dedicated action class. That keeps business logic in one testable place instead of spread across a fat controller, and it's easier to reuse from a job or a console command later.

What is the N+1 query problem and how do you fix it?

It happens when I loop over a collection and each iteration triggers its own query for a relationship, so 1 query for the list turns into N more queries. I fix it with eager loading, using with() to load the relationship up front in a single additional query instead of one per row. I also turn on strict mode in local development so Laravel throws if I forget and lazy-load by accident.

Query builder vs Eloquent, when do you use which?

Eloquent is built on top of the query builder and gives me models, relationships, events, and mutators, so I reach for it by default because it's more expressive and keeps behavior close to the data. I drop down to the plain query builder for reporting-style queries, bulk updates, or anything performance-sensitive where I don't need model hydration and just want raw rows back.

How do events and listeners work in Laravel?

An event is a simple class that represents something that happened, like OrderShipped, and one or more listeners react to it. I fire the event with a dispatch call, and Laravel runs every listener registered for it, which can also be queued so they run in the background instead of blocking the request. It's how I decouple side effects, like sending a notification, from the main action that triggered them.

Why would you push work onto a queue instead of doing it inline?

Anything slow or unreliable, like sending an email, calling a third-party API, or generating a report, I push onto a queue so the user gets a fast response instead of waiting on it. A job is just a class with a handle method, and a worker process pulls jobs off the queue and runs them, which also means a slow dependency can't take down the request cycle.

How do you use caching in Laravel?

I reach for Cache::remember when I have an expensive query or computation that doesn't need to be fresh on every request, so it either returns the cached value or runs the closure and stores the result for the given time. In production I run config:cache and route:cache to compile the config and routes into single files, which meaningfully speeds up boot time, but I have to remember to clear those after deploying a config change.

Sanctum vs Passport, how do you choose?

Sanctum is what I reach for by default. It handles both SPA session-based authentication and simple API tokens without the overhead of a full OAuth2 server. Passport implements full OAuth2, which I only need when I'm actually issuing tokens to third-party applications or need scopes and grant types like authorization code or client credentials.

staff

What is the service container and why does Laravel need it?

The container is Laravel's dependency injection tool. It knows how to build a class and its dependencies automatically, so I don't have to wire things up by hand everywhere. I bind an interface to a concrete implementation once, usually in a service provider, and then I can type-hint that interface anywhere and Laravel resolves it for me.

How do you handle failed jobs and retries?

I set tries and backoff on the job so it retries a limited number of times with increasing delay instead of hammering a failing service immediately. If it still fails after that, Laravel records it in the failed_jobs table, and I can inspect it, fix the underlying issue, and retry it manually with artisan. I also use the failed method on the job to clean up or notify someone when it exhausts retries.

How do you approach testing a Laravel application?

I write feature tests against the actual HTTP layer for the behavior that matters, like a request hitting a real route, middleware, and database, and I use factories to build realistic data instead of hardcoding fixtures. I use Pest for the expressive syntax on top of PHPUnit, and I reach for RefreshDatabase so each test starts clean instead of leaking state between tests.

principal

When is Laravel overkill?

For a small script, a single endpoint, or something with almost no persistence or business logic, the framework's conventions and boot time just add weight I don't need. I'd reach for something lighter, or even plain PHP, when I don't need the ORM, the queue system, or the container, and I'd only bring in Laravel once the app actually has enough moving parts, like auth, a real database layer, and background jobs, to justify it.

Fast recall

container = resolves dependencies automatically | provider = bootstraps bindings and boot logic | facade = static proxy to a container binding | middleware = filters request and response | eager loading = prevents the n+1 problem | scope = reusable chainable query logic | cast = attribute type conversion | migration = database schema version control | factory = generates fake test data | queue = runs work in the background | policy = model-based authorization class | sanctum = spa and api token auth | resource = controls the json response shape | schedule:run = the one cron entry laravel needs

BH·Laravel·github.com/bunlongheng/study