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


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Developer (Full-Stack)
Munich
Volunteer Vision GmbH
Full-Stack Developer
Tampa
Nu Image Medical
Senior Software Developer
Remote (US ONLY)/Kenilworth, NJ
Diversified
Senior Back-end Laravel API Developer - Immediate Contract (Full Time)
Remote
ApproveMe // Document Signing
Web Development Project Manager
Houston, TX
Swyft Filings
Experienced Laravel/VueJS Developer (Freelance)
Remote (preferably in the US)
Prosperly LLC
Senior React / Laravel Developer
Remote
The C.A.S.E. Engineering Group