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

October 26, 2018

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

<?php
        $user_id=123;
$user = User::findOrFail($user_id);
// 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.