How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

Laravel: How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

Use Eloquent's firstOrFail(). This is similar to findOrFail(), however findOrFail() does a 'WHERE id = ?' (assuming id is the primary key). With firstOrFail() it will return the first row based on whatever WHERE statements you have.

  1.  $user = User::where("email","[email protected]"->firstOrFail()

If you don't nt to throw an exception if none was found then you should just use first() (which will return null if nothing is found.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to sort an array in javascript?

How to check if two strings are anagrams in PHP?

What are macros in Laravel?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to use Anonymous classes in PHP 7?

How to change the order that migrations happen?

What is WordPress default Apache .htaccess rules?

What does 'final class' and 'final function' (final method) mean in PHP?

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?