A RESTful API built with Laravel 12 for managing travel orders, users, and notifications. The API follows modern Laravel best practices with standardized exception handling, proper HTTP status codes, and comprehensive Swagger/OpenAPI documentation.
- Requirements
- Installation
- Architecture
- Design Patterns
- Folder Structure
- API Documentation
- Authentication
- Response Format
- Exception Handling
- Commands
- WSL (Windows Subsystem for Linux) - for Windows users
- Docker and Docker Compose
- PHP 8.2+
- Composer
- Clone the repository:
git clone <repository-url>
cd orders-api- Install dependencies:
composer install- Start Docker containers using Laravel Sail:
./vendor/bin/sail up -d- Run migrations and seed the database:
./vendor/bin/sail artisan migrate:fresh --seed- Generate Swagger documentation:
./vendor/bin/sail artisan l5-swagger:generate- Access the application:
- API Base URL:
http://localhost - Swagger Documentation:
http://localhost/api/documentation
- API Base URL:
The application follows a layered architecture with clear separation of concerns:
┌─────────────────────────────────────┐
│ HTTP Request │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Routes (api.php) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Middleware (Sanctum Auth) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Form Request Validation │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Controllers │
│ (Business Logic & Orchestration) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Models (Eloquent) │
└──────────────┬──────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Database │
└─────────────────────────────────────┘
-
Controllers (
app/Http/Controllers/Api/V1/)- Handle HTTP requests
- Orchestrate business logic
- Return standardized JSON responses
-
Form Requests (
app/Http/Requests/)- Validate incoming requests
- Conditional validation based on route context
-
Resources (
app/Http/Resources/)- Transform models to API responses
- Ensure consistent data structure
-
Exceptions (
app/Exceptions/)- Custom exception classes
- Centralized error handling
-
Traits (
app/Http/Traits/)- Reusable response methods
- Standardized API responses
- Eloquent models act as repositories
- Data access abstraction through models
- API Resources transform model data
- Consistent response structure across endpoints
- Located in
app/Http/Resources/
ApiResponseTraitprovides reusable response methods- Controllers use traits for standardized responses
- Reduces code duplication
- Request validation separated from controllers
- Conditional validation based on route context
- Located in
app/Http/Requests/
- Global exception handling in
bootstrap/app.php - Custom exception classes for specific error types
- Centralized error response formatting
- Routes prefixed with
/api/v1/ - Allows for future API versions without breaking changes
- Standard CRUD operations via
apiResource - RESTful route naming conventions
orders-api/
├── app/
│ ├── Exceptions/ # Custom exception classes
│ │ ├── ApiException.php
│ │ ├── ResourceNotFoundException.php
│ │ └── UnauthorizedException.php
│ │
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── Controller.php # Base controller with Swagger annotations
│ │ │ └── Api/
│ │ │ └── V1/ # Version 1 API controllers
│ │ │ ├── TravelOrdersController.php
│ │ │ ├── UserController.php
│ │ │ └── UserNotificationsController.php
│ │ │
│ │ ├── Requests/ # Form request validation
│ │ │ ├── StoreTravelOrdersRequest.php
│ │ │ ├── StoreUserRequest.php
│ │ │ ├── StoreUserNotificationsRequest.php
│ │ │ └── UpdateTravelOrdersRequest.php
│ │ │
│ │ ├── Resources/ # API resource transformers
│ │ │ ├── TravelOrderResource.php
│ │ │ ├── UserResource.php
│ │ │ └── UserNotificationResource.php
│ │ │
│ │ └── Traits/ # Reusable traits
│ │ └── ApiResponseTrait.php
│ │
│ ├── Models/ # Eloquent models
│ │ ├── TravelOrders.php
│ │ ├── User.php
│ │ └── UserNotifications.php
│ │
│ └── Providers/ # Service providers
│
├── bootstrap/
│ └── app.php # Application bootstrap & exception handling
│
├── config/
│ ├── l5-swagger.php # Swagger configuration
│ └── ...
│
├── database/
│ ├── migrations/ # Database migrations
│ └── seeders/ # Database seeders
│
├── routes/
│ └── api.php # API routes
│
├── storage/
│ └── logs/ # Application logs
│
├── tests/ # Test files
│ ├── Feature/
│ └── Unit/
│
├── vendor/ # Composer dependencies
│
├── composer.json # PHP dependencies
├── docker-compose.yml # Docker configuration
├── phpunit.xml # PHPUnit configuration
└── README.md # This file
The API is fully documented using Swagger/OpenAPI. After starting the application, access the interactive documentation at:
Swagger UI: http://localhost/api/documentation
The documentation includes:
- All available endpoints
- Request/response schemas
- Authentication requirements
- Example requests and responses
- Try-it-out functionality
After making changes to controller annotations:
./vendor/bin/sail artisan l5-swagger:generateThe API uses Laravel Sanctum for token-based authentication.
Endpoint: POST /api/authenticate
Request Body:
{
"email": "admin@admin.com",
"password": "password"
}Response:
{
"success": true,
"data": {
"token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
"message": "Token created successfully",
"status_code": 200
}Include the token in the Authorization header for all protected routes:
Authorization: Bearer {your-token-here}
Note: Only users with the name "Admin" can create access tokens via /api/authenticate. Regular users should use /api/v1/userLogin for authentication.
All API responses follow a standardized format:
{
"success": true,
"data": {
// Response data here
},
"message": "Success message",
"status_code": 200
}{
"success": false,
"message": "Error message",
"status_code": 400,
"errors": {
// Validation errors (if applicable)
}
}200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found422- Validation Error500- Internal Server Error
The application implements centralized exception handling:
ApiException- Base exception for API errorsResourceNotFoundException- 404 errorsUnauthorizedException- 401 errors
Located in bootstrap/app.php, the handler:
- Catches all exceptions for API routes
- Formats errors consistently
- Logs exceptions for debugging
- Returns appropriate HTTP status codes
ModelNotFoundException→ 404ValidationException→ 422AuthenticationException→ 401QueryException→ 500NotFoundHttpException→ 404- Custom
ApiException→ Custom status code
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/authenticate |
Get access token (Admin only) | No |
| POST | /api/v1/userLogin |
User login | Yes |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/v1/users |
List all users | Yes |
| POST | /api/v1/users |
Create user | Yes |
| PUT | /api/v1/users/{id} |
Update user | Yes |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/v1/orders |
List all orders | Yes |
| POST | /api/v1/orders |
Create order | Yes |
| GET | /api/v1/orders/{id} |
Get order | Yes |
| PUT | /api/v1/orders/{id} |
Update order | Yes |
| DELETE | /api/v1/orders/{id} |
Delete order | Yes |
| POST | /api/v1/filterOrders |
Filter orders | Yes |
| POST | /api/v1/ordersByUser |
Get orders by user | Yes |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/v1/notifications |
List all notifications | Yes |
| POST | /api/v1/notifications |
Create notification | Yes |
| GET | /api/v1/notifications/{id} |
Get notification | Yes |
| DELETE | /api/v1/notifications/{id} |
Delete notification | Yes |
| POST | /api/v1/showUserNotifications |
Get notifications by user | Yes |
# Start Docker containers
./vendor/bin/sail up -d
# Stop Docker containers
./vendor/bin/sail down
# View logs
./vendor/bin/sail artisan tail
# Run migrations
./vendor/bin/sail artisan migrate
# Run migrations with seed
./vendor/bin/sail artisan migrate:fresh --seed# Run all tests
./vendor/bin/sail artisan test
# Run specific test suite
./vendor/bin/sail artisan test --testsuite=Feature# Generate Swagger documentation
./vendor/bin/sail artisan l5-swagger:generate
# Clear cache
./vendor/bin/sail artisan cache:clear
./vendor/bin/sail artisan config:clear# List all routes
./vendor/bin/sail artisan route:list
# List API routes only
./vendor/bin/sail artisan route:list --path=api- Orders cannot be cancelled if the start date is less than 30 days away
- When attempting to cancel, the API returns a 400 error with an appropriate message
- Only users with the name "Admin" can create access tokens via
/api/authenticate - Regular users authenticate via
/api/v1/userLogin - All protected routes require a valid Sanctum token
- Laravel 12 - PHP Framework
- Laravel Sanctum - API Authentication
- L5-Swagger - API Documentation
- Docker & Laravel Sail - Development Environment
- MySQL - Database
- PHPUnit - Testing Framework
- Create a feature branch
- Make your changes
- Write/update tests
- Ensure all tests pass
- Update documentation if needed
- Submit a pull request