How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

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

Use Eloquent's findOrFail($id) method - this will find a model by its primary key or throw an exception.

  1.         $user_id=123;
  2. $user = User::findOrFail($user_id);
  3. // if it cannot find a row with $user_id as the primary key, it will throw a \Illuminate\Database\Eloquent\ModelNotFoundException\ModelNotFoundException exception

If you don't want to throw an exception if none was found then you should just use find() (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 find an item by Primary Key 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 replace whitespace with a single space

How to reverse htmlentities() / What is the opposite of htmlentities()?

How does PHP compare objects?

How to block access to certain referrers in Apache using .htaccess

How to force SSL in Apache's .htaccess?

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to select what columns to return when calling ::all()

How to use Anonymous classes in PHP 7?

How to set custom HTTP headers in Apache (by editing .htaccess)

What is the difference between integration and unit tests?