I am using Laravel 5.3. I have few APIs where user will request for specific id.
For example url to subscribe an eventexample.com/api/event/{id}/subscribe
Normally if id
not exist, Laravel will return response 500 with error message "Trying to get property of non-object"
So I would add check if event is exist like below in every controller where model 'id' id passed:
$event = Event::find($id)
if ($event) {
// return json data
}
else {
return response()->json([
'status' => 'object not found'
], 404);
}
My question is, any better solution to handle this globally to check if object requested is not exist? My current solution is here, but I might think there should be better one
I add this code into my app/Exception/Handler.php
, so every api request non-existing object will return 404 with specific json message. So the API consumer will know the object id not valid.
public function render($request, Exception $exception)
{
// global exception handler if api request for non existing object id
if ($request->wantsJson() && $exception->getMessage() == 'Trying to get property of non-object') {
return response()->json([
'status' => 'object requested not found'
], 404);
}
return parent::render($request, $exception);
}
Thanks in advance!
You can use render()
function of App\Exceptions\Handler
class as:
public function render($request, Exception $exception)
{
if ($request->wantsJson() && $exception instanceof ModelNotFoundException) {
return response()->json(['status' => 'object requested not found'], 404);
}
return parent::render($request, $exception);
}
And remember to add following code:
use Illuminate\Database\Eloquent\ModelNotFoundException;
Docs
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