Laravel 5.7 Guest User Gates

Tutorials

September 5th, 2018

Laravel 5.7 Guest User Gates

In Laravel 5.6 and below authorization gates and policies automatically return false for unauthenticated users. New in Laravel 5.7, you can now allow guests to go through authorization checks by using a nullable type-hint or setting the default value as null:

<?php
 
Gate::define('view-post', function (?User $user) {
// Guests
});

By using a nullable type hint the $user variable will be null when a guest user is passed to the gate, and you can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization.

If you don’t use a nullable type hint, guests will automatically get this beautiful 403 response for Laravel 5.7, designed by Steve Schoger (@steveschoger):

Laravel 5.7 was released Tuesday, September 4th. Check out what’s new in the documentation’s Release Notes and by visiting our Laravel 5.7 – A Look At What’s New section.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.