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
Laravel News Partners

Laravel Jobs

Senior Full Stack Engineer - Laravel
Laravel partner seeks Lead Developer
Kirschbaum Development Group
Senior Programmer **Immediate Opening** (send resume to
SBG Corp
Web Developer - Laravel
Grand Forks, North Dakota
Center for Rural Health
Senior Full-Stack Laravel Developer
Berlin, Germany


Join 31,000+ others and never miss out on new tips, tutorials, and more.