Laravel Tutorials

Laravel firstOrFail forTheWin

Published

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.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Sponsored

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Validate and Convert HEIC Images in Laravel image

Validate and Convert HEIC Images in Laravel

Read article
Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues image

Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Read article
Reject Unexpected Array Keys with Laravel Validation image

Reject Unexpected Array Keys with Laravel Validation

Read article
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article