Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 policies how to redirect unauthorized users

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

like image 971
Kris MP Avatar asked Sep 17 '16 14:09

Kris MP


1 Answers

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.

like image 120
Muhammad Maulana Avatar answered Oct 01 '22 23:10

Muhammad Maulana