To create Laravel ACL, you can follow the steps below:
Step 1: Install Laravel
To get started, you first need to install Laravel using Composer. You can run the following command to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel acl-app
Step 2: Install Laravel's Authorization Package
Next, you need to install Laravel's authorization package, which will allow you to define and manage roles and permissions. You can install it using the following command:
composer require laravel/ui
php artisan ui vue --auth
composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
Step 3: Create Roles and Permissions
After installing the package, you need to create roles and permissions. You can do this by defining them in the AuthServiceProvider.php file in the boot() method:
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
public function boot()
{
$this->registerPolicies();
Role::create(['name' => 'admin']);
Role::create(['name' => 'editor']);
Permission::create(['name' => 'create post']);
Permission::create(['name' => 'edit post']);
Permission::create(['name' => 'delete post']);
}
Step 4: Assign Roles and Permissions to Users
Once you have created roles and permissions, you can assign them to users. You can do this in your application's controllers or in your routes:
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$user = User::find(1);
$role = Role::findByName('admin');
$user->assignRole($role);
$permission = Permission::findByName('create post');
$user->givePermissionTo($permission);
Step 5: Protect Routes and Actions
Finally, you can protect your routes and actions by using Laravel's built-in authorize() method:
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
class PostController extends Controller
{
public function create()
{
$this->authorize('create post');
// Create new post
}
public function edit($id)
{
$this->authorize('edit post');
// Edit post with id = $id
}
public function delete($id)
{
$this->authorize('delete post');
// Delete post with id = $id
}
}
By following these steps, you can create Laravel ACL and manage roles and permissions in your application.
No comments:
Post a Comment