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 run an artisan command from a controller

How to round a number in JS?

How do Invokable Controllers work in Laravel?

When is __destruct called in PHP?

An overview of every main PHP array function

Why should you update APP_URL from from http://localhost?

What kind of database field type should you (normally) use for foreign keys?

Is multiple inheritance supported in PHP?

How to query mysql using PDO in PHP?

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)