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 do you launch the PHP interactive shell?

How to install jpegtran for Linux CentOS

What is the difference between var, let and const in Javascript?

Point all requests to one PHP file

Is multiple inheritance supported in PHP?

How to Extract Query String (from a URL) Into an Associative Array in PHP

How to view all installed PHP modules?

How to undelete a soft deleted Eloquent row?

How to autoload helper files with composer?

How to see all of the options for an artisan command?