I have a project and if I want to access partner/X
I got get property of non object
error, becouse I have less partners than X.
My question. How to tell the controller, that if the result of the modelquery is empty, than throw a 404 error
?
My code is so far:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
$partner = Partner::find($id);
if (empty($partner)){
return ???
}
}
}
Through your config/app. php , set 'debug' => env('APP_DEBUG', false), to true . Or in a better way, check out your . env file and make sure to set the debug element to true.
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler.
Laravel has a specific method for that. If you use findOrFail($id)
, it will throw an Illuminate\Database\Eloquent\ModelNotFoundException
, so there's no need to throw an Exception by yourself.
If you mean "show the user an 404 error" instead of literally throwing an Exception, then catch it and abort()
:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
try {
$partner = Partner::find($id);
// do your work
}
catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
abort(404, "The Partner was not found");
}
}
}
Read more about this here.
Use the abort()
helper:
abort(404);
There's also abort_if()
and abort_unless()
if you prefer. Whichever one you choose, you can pass it the required status code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With