ianmcqueen's avatar

Best Way To Check If Record Exists

Hi there,

I have an ItemsController.php that has route model binding to the Item model:

RouteServiceProvider.php

$router->bind('items', function($value) {
    return \App\Item::where('slug', $value)->firstOrFail();
});

ItemsController.php

public function show(Item $item)
{
    return view('items.show', compact('item'));
}

What is the Laravel convention for checking if a record exists on this method (i.e. handling No query results for model [App\Item])? A try, catch block in the controller method?

New to Laravel. Asking about the basic standard here. Thanks in advanced!

0 likes
4 replies
dennisvdv's avatar

I think this should work.

return \App\Item::where('slug', $value)->exists();

4 likes
joedawson's avatar

What you're doing is fine, would you like to display a 404 page of some sort if no model is found?

For Laravel 5.1, open up your Handler.php file in app/Exceptions and implement this into your render() method.

if ($e instanceof ModelNotFoundException) {
    $e = new NotFoundHttpException($e->getMessage(), $e);
}

This now throws a NotFoundHttpException for all ModelNotFoundException's. Meaning you can simply create a 404.blade.php file in resources/views/errors and Laravel will know to use that view to display a 404 page.

But, if you're using 5.2 then you can go ahead and skip the part where you amend your Handler.php file and just create the 404.blade.php file.

ianmcqueen's avatar

Thank you guys. This is helpful!

Actually, what I was hoping to do was to display my own custom view completely, and for this specific method. What is the Laravel standard way of catching this in a controller method?

dwainb's avatar

The answer provide dennisvdv solved my issue here.

return \App\Item::where('slug', $value)->exists();

I did; use App\Item

$answer = Item::where('slug', $value)->exists(); // this returns a true or false

Then I use if statements to handle the rest of my logic.

Please or to participate in this conversation.