Ildar Ildar - 1 year ago 358
PHP Question

Guest users in laravel authorization policies

I use policies for user authorization. How to use policies for guest users?

Here is my code:

In controller:

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

In policy:

class PostPolicy
// This function executes only for authenticated users.
// I want to use it for guest users too
public function index(User $user)
return $user->can('get-posts');

Answer Source

First make a new service provider:

php artisan make:provider GuestServiceProvider

Then edit GuestServiceProvider.php with this:

public function boot()
    // Laravel policies only work if the user isn't null so for guest access we need to assign a dummpy user.
    // From now on to check for guest use is_null(Auth::user()->getKey())
    if(!Auth::check()) {
        $userClass = config('auth.providers.users.model');
        Auth::setUser(new $userClass());

Now Policies will work for guest users and in your policy you can check for the guest by doing:

    // it's a guest

Which essentially means if the user doesn't have an id then its not a real user, hence must be a guest.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download