Laravel 5.3 policies how to redirect unauthorized users

Kris MP picture Kris MP · Sep 17, 2016 · Viewed 20.2k times · Source

I can't find it on the documentation. How to redirect unauthorized user?

RolePolicy.php

class RolePolicy
{
    use HandlesAuthorization;

    public function manageRoles(User $user)
    {
        return $user->isAdmin();
    }
}

RolesController.php

function __construct()
{
    $this->authorize('manageRoles', Role::class);
}

Thanks in advance

Answer

Muhammad Maulana picture Muhammad Maulana · Sep 28, 2016

You can modify file app\Exceptions\Handler.php

on the render function:

public function render($request, Exception $e)
{

    /**modified part**/  
    if ($request->wantsJson()) {
        return response([
            'success' => false,
            'message' => $e->getMessage()
        ], 404);
    }

    if ($e instanceof AuthorizationException) {
        return redirect('path');

        //or simply
        return view('errors.forbidden');
        //but this will return an OK, 200 response.
    }
    /**end of modified part**/

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

If you want to put a 403, use helper function response(). You can see the documentation for responses here https://laravel.com/docs/master/responses

Basically you can use the solution to play with more options. But the easiest way is just to create a view file: errors/403.blade.php and that view will automatically load when you hit unauthorized exceptions. The same will work for 404 not found, just create the 404.blade.php.