How to throw exception if no data in laravel?

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

How to throw exception if no data in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 10 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.

Related Threads:

How to throw exception in PHP?
How to throw an exception in PHP?
How to handle exception in middleware laravel?
How to manually catch error exception in laravel?
How to handle server side exception in laravel?
How to count the number of data in laravel?