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

October 26, 2018

Use Eloquent's firstOrFail(). This is similar to findOrFail(), however findOrFail() does a 'WHERE id = ?' (assuming id is the primary key). With firstOrFail() it will return the first row based on whatever WHERE statements you have.

<?php
 $user = User::where("email","test@example.com"->firstOrFail() 

If you don't nt to throw an exception if none was found then you should just use first() (which will return null if nothing is found.