R
R
Roman Sarvarov2021-07-13 17:06:29
Laravel
Roman Sarvarov, 2021-07-13 17:06:29

How to check the action in the policy on an unlogged user?

I'm in the view controller (I have a spa on vue.js) in the form of JSON I give some user rights, like this:

return [
    'post' => $post, 
    'permissions' => [
        'view' => auth()->user()->can('view', $post),
        'edit' => auth()->user()->can('edit', $post),
        'delete' => auth()->user()->can('delete', $post),
    ],
]);


I know that if you put before the argument type in the arguments of the policy method, ?then the policy can be checked for guests too .
But the question is - how to do it in the controller? If the user is not logged in, it auth()->user()will return null.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin B., 2021-07-13
@megakor

Stop using the Auth facade. Instead, use Gates, which is exactly what they are designed to solve your problem.

J
jazzus, 2021-07-13
@jazzus

In the controller you need to use $this->authorize('update', $post) or constructor for resource controllers

P
pLavrenov, 2021-07-13
@pLavrenov

Auth::user()
Auth::guest()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question