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 first()
(which will return null if nothing is found.