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:

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x