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

Issue

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 App\Http\Controllers;

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

This is my file FontController:

<?php

namespace App\Http\Controllers;

use App\Http\Resources\BaseCollection;
use App\Http\Resources\FontResource;
use App\Models\Design;
use App\Models\Font;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Enums\CursorPaginate;
use App\Enums\ResponseMessages;
use App\Http\Resources\DesignResource;
use Illuminate\Support\Facades\Redis;

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

Solution

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 App\Models\Font;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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.

Answered By – Rwd

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published