A comprehensive guide and implementation of Laravel Policies for managing authorization in Laravel applications. This project demonstrates how to implement role-based access control (RBAC) using Laravel's policy system.
Here I shows how to implement a robust authorization system in Laravel using Policies. It includes:
- Role-based access control
- User and Post management
- API authentication using Laravel Sanctum
- Policy-based authorization for different user roles
- PHP 8.1 or higher
- Composer
- MySQL or another database system
- Laravel 10.x
- Clone the repository:
git clone https://github.com/murilolivorato/laravel_acl_policies.git
cd laravel_acl_policies
- Install dependencies:
composer install
- Create and configure your
.env
file:
cp .env.example .env
- Generate application key:
php artisan key:generate
- Run migrations and seed the database:
php artisan migrate
php artisan db:seed
- Install Laravel Sanctum:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
The project implements a role-based authorization system with the following key components:
User
- Handles user authentication and role relationshipsRole
- Manages user rolesPost
- Represents blog posts with user ownership
PostPolicy
- Controls access to post-related actionsUserPolicy
- Manages user-related permissions
-
Role-Based Access Control
- Super Admin role with full access
- Manager role with limited access
- Custom role permissions
-
Policy Implementation
- View permissions
- Create/Update permissions
- Delete permissions
- Own resource management
-
API Authentication
- Token-based authentication using Sanctum
- Role-specific abilities
- Secure API endpoints
POST /api/login
- User loginPOST /api/logout
- User logout (requires authentication)
GET /api/users
- List usersGET /api/users/{user}
- Get specific userPOST /api/users
- Create userPUT /api/users/{user}
- Update userDELETE /api/users/{user}
- Delete user
GET /api/posts
- List postsGET /api/posts/{post}
- Get specific postPOST /api/posts
- Create postPUT /api/posts/{post}
- Update postDELETE /api/posts/{post}
- Delete post
- Can view own user profile
- Can create, update, and delete own posts
- Can view own posts
- Can view all users
- Can manage all posts
- Full access to all resources
- Login to get your authentication token:
curl -X POST http://your-domain/api/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password"}'
- Use the token for authenticated requests:
curl -X GET http://your-domain/api/posts \
-H "Authorization: Bearer {your-token}"
Murilo Livorato
- GitHub: murilolivorato
- LinkedIn: Murilo Livorato
This project is open-sourced software licensed under the MIT license.
This tutorial was inspired by concepts from Jeremy McPeak's Laravel API Master Class on Laracasts.