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 Extract Query String (from a URL) Into an Associative Array in PHP

How to add comments in PHP

What is camel case?

Remove trailing slash (redirect to remove trailing slash) in .htaccess

301 Redirect a single URL in .htaccess to a new location

How to set up an alias to map one directory to another destination

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

Force trailing slash (redirect if no trailing slash exists) in .htaccess

What is the null coalescing operator in PHP7?

What is the max size, by default, of GET variables?