php – Guest authorization in laravel 5.2


I am using laravel policies for authorization. The problem is they don't work for guests. How can I check the rights for guests?

My code:

In the controller:

class PostController extends Controller
    public function index(Post $post)
        return $post->all();

In politics:

class PostPolicy
    // Эта функция выполняется только для аутентифицированных пользователей. 
    // Хотелось бы, чтобы она выполнялась и для гостей
    public function index(User $user)
        return $user->can('get-posts');

I need the ability to restrict access to controller methods for some users. The rights will be stored in the database and can be changed through the admin panel. It seems to me that the standard policy mechanism is suitable for this, where I could check access to each controller method + using the entrust module, roles and privileges for users are stored in the database. And on any request, I can check the permissions using the $ user-> can () method. But that doesn't work for the guests. I do not understand why this is done, because users also have rights. And it is not clear how to check now whether users have privileges for any action


It all depends, of course, on how big your application will be. But I can draw your attention to middleware, this kind of check is usually enough for small applications. If you need to bind rights specifically to each user and his role in the system, you can implement this yourself by wrapping the existing User but if you do not want to reinvent the wheel, then you should go here , this is not the only package and there are many of them laravel access rights user keyword 🙂

Scroll to Top