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)
{
$this->authorize($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');
}
}
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:
if(is_null(Auth::user()->getKey())){
// 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.
In your PostPolicy change this
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');
}
}
to:
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');
}
}
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With