Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5 render AccessDeniedHttpException

Why is it not rendered in a given way? Other types of exceptions are working well except AccessDeniedHttpException

App/Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException as AccessDeniedHttpException;
... 

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
...
            // 403 Forbidden
            if ($exception instanceof AccessDeniedHttpException)
            {
                return response()->json([
                    'code' => 403,
                    'message' => 'This action is unauthorized1.',
                ],403);
            }
            // 401 Unauthorized
            if ($exception instanceof AuthenticationException)
            {
                return response()->json([
                    'code' => 401,
                    'message' => 'Unauthenticated error.',
                ],  401);
            }

The 401 is working like a charm, but the 403 do the original rendering.

Any solutions?

like image 376
Prancz Ádám Avatar asked Oct 15 '25 06:10

Prancz Ádám


2 Answers

Try and include this in your App\Exceptions\Handler.php. Be sure to add use Illuminate\Auth\Access\AuthorizationException; at the top of your Hander.php:

protected $dontReport = [
    \Illuminate\Auth\Access\AuthorizationException::class,
];

Apparently, AccessDeniedHttpException is an instance of AuthorizationException.

public function render($request, Exception $exception)
{
    //Useful since some methods cannot be accessed in certain URL extensions
    if ($exception instanceof AuthorizationException) {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $exception);
}
like image 136
Josh D. Avatar answered Oct 18 '25 04:10

Josh D.


class CouponStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;//please change the authorize return to true in request file.
    }
like image 29
ganicvp7 Avatar answered Oct 18 '25 05:10

ganicvp7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!