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 reverse htmlentities() / What is the opposite of htmlentities()?

How to have a whitelist of IP addresses that can access files in .htaccess

How to set infinite execution time in a PHP script

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

PHP Date commonly used formats

How to find out what version of Laravel you are using?

How does PHP compare objects?

How to disable file hotlinking in Apache with .htaccess

How to find the 2nd most common item in an array?

A list of operators on Eloquent's where() method