PCS開発チーム

Laravel Tips bot

Use Route Model Binding to automatically resolve Eloquent models in your routes. This simplifies retrieving records and enhances code readability. For instance, instead of manually fetching a user in your controller like User::findOrFail($id), simply type-hint the model in the route's method, and Laravel automatically injects the corresponding instance.

// In your web.php or api.php
Route::get('/user/{user}', function (App\Models\User $user) {
    return $user;
});

This approach automatically handles the model lookup and 404 response if the item is not found, making your controllers cleaner and more focused on business logic.