If using spatie, and of course only a suggestion, use the spatie examples:
https://spatie.be/docs/laravel-permission/v5/introduction
Throughout their documentation they have many examples.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to add roles and permissions to a laravel forum app based on the tutorial here: Creating a Laravel Forum Using Laravel 8
However, this tutorial that demonstrates how to add roles and permissions manually without a package using a single guard, User Policy, Middleware and a LoginResponse class to handle redirection based on the role of the auth user.
I'm attempting to do something similar using the Spatie/Laravel-Permissions package. When doing this, I'm finding that the HasAnyRole method and the Can method are not recognized in certain areas of the code as shown below. Another reason I'm asking is that doing this with a Policy seems redundant.
Do I need policies (guards and gates?)? Is there a more efficient, cleaner way of adding roles and permissions using spatie/laravel-permissions?
use HasRoles;
const DEFAULT = 1;
const MODERATOR = 2;
const ADMIN = 3;
/** A type column was added to the User table migration **/
public function type(): int
{
return (int) $this->type;
}
public function isModerator(): bool
{
return $this->type() === self::MODERATOR;
}
public function isAdmin(): bool
{
return $this->type() === self::ADMIN;
}
const ADMIN = 'admin';
public function admin(User $user): bool
{
return $user->isAdmin();
}
UserPolicy reference is added here
protected $policies = [
User::class => UserPolicy::class;
];
Note: One issue I'm having here is that the "can" method is not recognized in the Auth
class CheckIfAdmin
{
public function handle(Request $request, Closure $next, $guard = null) {
// In this condition, the hasAnyRole() method is not found in Auth::guard($guard)->user()
if(Auth::guard($guard) && Auth::guard($guard)->user()->hasAnyRole(['super-admin', 'admin']) ){
//
}
// Also, in this condition, the can() method is not found in Auth::guard($guard)->user()
if(Auth::guard($guard)->user()->can(UserPolicy::ADMIN, User::class) {
return $next($request);
}
throw new HttpException(403, 'Forbidden');
}
}
No errors found in this code according to PHPStorm.
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as ContractsLoginResponse;
class LoginResponse implements ContractsLoginResponse
{
public function toResponse($request)
{
if (auth()->user() && auth()->user()->hasRole('administrator')) {
return redirect()->route('admin.index');
}
return redirect()->intended(config('fortify.home'));
}
}
Please or to participate in this conversation.