How to throw exception if no data in laravel?

by dalton_moen , in category: PHP Frameworks , 3 months ago

How to throw exception if no data in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 3 months ago

@dalton_moen 

In Laravel, you can throw an exception if there is no data by using the findOrFail method on the Eloquent model.


Here is an example:

1
2
3
4
5
6
7
8
use AppModelsUser;
use IlluminateDatabaseEloquentModelNotFoundException;

try {
    $user = User::findOrFail($userId);
} catch (ModelNotFoundException $e) {
    throw new Exception('No data found for user with ID: ' . $userId);
}


In this example, the findOrFail method will try to retrieve a user with the given $userId. If no user is found, a ModelNotFoundException will be thrown. You can catch this exception and then throw a new Exception with a custom message to indicate that no data was found.