Check if the request record exists in the method show()

Check if the request record exists in the method show() .If they do not exist call the method DislayNotFound.

Have any of you tried this method? Can you help me?

This is my file BaseController:

<?php

namespace AppHttpControllers;

class BaseController extends Controller
{
    public function display_not_found ()
    {
        return response(['message' => 'Not found'], 404);
    }
}

This is my file FontController:

<?php

namespace AppHttpControllers;

use AppHttpResourcesBaseCollection;
use AppHttpResourcesFontResource;
use AppModelsDesign;
use AppModelsFont;
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;
use AppEnumsCursorPaginate;
use AppEnumsResponseMessages;
use AppHttpResourcesDesignResource;
use IlluminateSupportFacadesRedis;

class FontController extends BaseController
{
 public function show(Font $font)
    {
        if(!$font->exists()){
            return $this->display_not_found();
        }

        if($font['user_id'] !== auth()->user()->id) {
            return response(['message' => 'Forbidden'], 403);
        }

        return new FontResource($font);
    }
}

Error:

enter image description here

Answer

If you would like to change the error response, you can override the Exception Hander. To do this, add the following to the register method in your your app/Exceptions/Handler.php file:

$this->renderable(function (NotFoundHttpException $e, $request) {
    $previous = $e->getPrevious();

    if (
        $previous instanceof ModelNotFoundException &&
        $previous->getModel() === Font::class &&
        $request->expectsJson()
    ) {
        return response()->json(['message' => 'Not found'], 404);
    }
});

Don’t forget to import the necessary classes are the top:

use AppModelsFont;
use IlluminateDatabaseEloquentModelNotFoundException;
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;

Alternatively, you could remove route model binding for this method (the easiest way to do this would be to remove the Font type hint) and manually try to find the model.