Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to react to not found records when using Eloquent's find method in laravel?

Since I have not been able to find any info about this while browsing the net, I'd like to answer how do you react to the situation when Eloquent does not find the specified record in your table.

An example of this would be, let's say, a user is trying to edit a page with an ID that does not exists, so he tries to go to somesite.com/pages/edit/1; hwoever, the page with ID 1 does not exist.

My question would be, whether you use the built-in findOrFail() method that displays the generic error message or whether a better solution would be to always check whether the specified record is there and if not then throw an exception?

Thanks in advance.

like image 712
crzpiot Avatar asked Sep 02 '25 15:09

crzpiot


1 Answers

The better option will be using findOrFail (if looking by id) or firstOrFail (if looking not by id). This way you Laravel automatically throws exception and you can make redirection or display 404 page.

However if you want to make for example custom redirection (for example in one case redirection to mainpage, in other to for example some pages page), you can catch the exception in each controller and then make redirection for example:

try {
   $record = Page::findOrFail(1);
}
catch (ModelNotFoundException $e) {
   // here you can make redirection, log or anything you want
}
like image 189
Marcin Nabiałek Avatar answered Sep 05 '25 06:09

Marcin Nabiałek