1$user->assignRole('writer');
2
3// You can also assign multiple roles at once
4$user->assignRole('writer', 'admin');
5// or as an array
6$user->assignRole(['writer', 'admin']);
7
1// Install package
2composer require spatie/laravel-permission
3
4// config/app.php
5'providers' => [
6 // ...
7 Spatie\Permission\PermissionServiceProvider::class,
8];
9
10// Publish config file
11php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
12
13// Clear cache
14php artisan optimize:clear
15 # or
16php artisan config:clear
17
18// Run migration to create tables
19php artisan migrate
20
1User::whereHas("roles", function($q){ $q->where("name", "Member"); })->get()
2
1cd ~/Sites
2laravel new mypermissionsdemo
3cd mypermissionsdemo
4git init
5git add .
6git commit -m "Fresh Laravel Install"
7
8# Environment
9cp -n .env.example .env
10sed -i '' 's/DB_CONNECTION=mysql/DB_CONNECTION=sqlite/' .env
11sed -i '' 's/DB_DATABASE=/#DB_DATABASE=/' .env
12touch database/database.sqlite
13
14# Package
15composer require spatie/laravel-permission
16php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
17git add .
18git commit -m "Add Spatie Laravel Permissions package"
19php artisan migrate:fresh
20
21# Add `HasRoles` trait to User model
22sed -i '' $'s/use Notifiable;/use Notifiable;\\\n use \\\\Spatie\\\\Permission\\\\Traits\\\\HasRoles;/' app/User.php
23sed -i '' $'s/use HasFactory, Notifiable;/use HasFactory, Notifiable;\\\n use \\\\Spatie\\\\Permission\\\\Traits\\\\HasRoles;/' app/Models/User.php
24git add . && git commit -m "Add HasRoles trait"
25
26# Add Laravel's basic auth scaffolding
27composer require laravel/ui --dev
28php artisan ui bootstrap --auth
29# npm install && npm run prod
30git add . && git commit -m "Setup auth scaffold"
31