Laravel firstOrFail forTheWin

Tiny controllers are so attractive and crisp. I love it when you are able to have a simple two line method but still keep all the functionality you need. A common pattern in building CRUD applications is showing a record by id or slug and I want to show how to easily set this up.

Here is my controller method:

public function getPost($slug) { $post = Post::where('slug', '=', $slug)->firstOrFail(); return View::make(‘details’, compact(‘post’)); }

And the last step is to listen for the exception which I add in filters.php:

use IlluminateDatabaseEloquentModelNotFoundException; App::error(function(ModelNotFoundException $e) { return Response::make('Not Found', 404); });

This is covered in the Laravel documentation but I think it’s so beautiful that I wanted to highlight it.

Filed in: Laravel Tutorials