Hula Hula
Hula Hula

Reputation: 573

Custom findOrFail for the API routes

I think this should be implemented by default since I'm working in routes/api.php.

I want to give a 404 error JSON response in case that we don't find any rows for the given id argument on findOrFail() method.

Something like:

return response()->json([
    'status' => 'ERROR',
    'error' => '404 not found'
], 404);

Instead of the default Sorry, the page you are looking for could not be found. blade page.

I don't want to do:

$item = Model::find($id);
if (is_null($item)) {
    return response()->json([
        'status' => 'ERROR',
        'error' => '404 not found'
    ], 404);
}

Everywhere when I getting an id, and I wouldn't like to implement this in a middleware since it will cause some 'mess' on the api.php file.

Upvotes: 10

Views: 10088

Answers (4)

Md Rafsan Jani Rafin
Md Rafsan Jani Rafin

Reputation: 175

Add this in app/Exceptions/Handler.php

use Illuminate\Database\Eloquent\ModelNotFoundException;

public function render($request, Throwable $e)
    {
        if ($request->expectsJson()) {
            if ($e instanceof ModelNotFoundException) {
                return response()->json([
                    'message' => 'Record not found.',
                ], 404);
            }
        }

        return parent::render($request, $e);
    }

Upvotes: 3

Richard Fu
Richard Fu

Reputation: 626

Or use this, looks cleaner to me:

try {
    $resource = Model::findorfail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    return response([
        'status' => 'ERROR',
        'error' => '404 not found'
    ], 404);
}

Upvotes: 6

Robert Brisita
Robert Brisita

Reputation: 5844

Just to add, I ended up checking for these three exceptions:

  1. Illuminate\Database\Eloquent\ModelNotFoundException;
  2. Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  3. Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

And then returning JSON if expected:

if ($request->expectsJson()) {
    return response()->json(['error' => $msg], $code);    
}

Upvotes: 4

pseudoanime
pseudoanime

Reputation: 1593

You can always catch the exception in the App\Exceptions\Handler.php

Import the exception into the class using the following:

use \Illuminate\Database\Eloquent\ModelNotFoundException;

and in the render method, add

if ($e instanceof ModelNotFoundException) {

            return response()->json([
                'message' => 'Record not found',
            ], 404);

        }

Upvotes: 18

Related Questions