Files
Laravel-Docker-Dev-Template/docs/laravel-setup.md
2026-03-06 08:57:05 +02:00

264 lines
5.6 KiB
Markdown

# Laravel Base Setup Guide
This guide covers setting up authentication, API, and base middleware for your Laravel application.
## Quick Start
After installing Laravel and running `make setup-tools`, run:
```bash
make setup-laravel
```
This interactive script will:
1. Set up authentication (Breeze or Jetstream)
2. Configure Sanctum for API authentication
3. Create security middleware
4. Set up storage symlink
## Authentication Options
> **This template focuses on Blade and Livewire** - no JavaScript frameworks (Vue/React/Inertia). This keeps debugging simple and server-side.
### Laravel Breeze + Blade (Recommended)
Best for: Most applications. Simple, fast, easy to debug.
Features:
- Login, registration, password reset
- Email verification
- Profile editing
- Tailwind CSS styling
```bash
composer require laravel/breeze --dev
php artisan breeze:install blade
php artisan migrate
npm install && npm run build
```
### Laravel Breeze + Livewire
Best for: Apps needing reactive UI without JavaScript frameworks.
Same features as Blade, but with dynamic updates via Livewire.
```bash
composer require laravel/breeze --dev
php artisan breeze:install livewire
php artisan migrate
npm install && npm run build
```
### Laravel Breeze API Only
Best for: When you want to build your own Blade views.
Provides API authentication endpoints, you build the frontend.
```bash
composer require laravel/breeze --dev
php artisan breeze:install api
php artisan migrate
```
### Laravel Jetstream + Livewire (Full-featured)
Best for: SaaS applications needing teams, 2FA, API tokens.
Features:
- Profile management with photo upload
- Two-factor authentication
- API token management
- Team management (optional)
- Session management
- Browser session logout
```bash
composer require laravel/jetstream
php artisan jetstream:install livewire --teams
php artisan migrate
npm install && npm run build
```
## API Authentication (Sanctum)
Laravel Sanctum provides:
- SPA authentication (cookie-based)
- API token authentication
- Mobile app authentication
### Creating Tokens
```php
// Create a token
$token = $user->createToken('api-token')->plainTextToken;
// Create with abilities
$token = $user->createToken('api-token', ['posts:read', 'posts:write'])->plainTextToken;
```
### Authenticating Requests
```bash
# Using token
curl -H "Authorization: Bearer YOUR_TOKEN" https://your-app.com/api/user
# Using cookie (SPA)
# First get CSRF token from /sanctum/csrf-cookie
```
### Token Abilities
```php
// Check ability
if ($user->tokenCan('posts:write')) {
// Can write posts
}
// In route middleware
Route::post('/posts', [PostController::class, 'store'])
->middleware('ability:posts:write');
```
## Security Middleware
The setup script creates two middleware files:
### ForceHttps
Redirects HTTP to HTTPS in production.
```php
// Register in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\ForceHttps::class);
})
```
### SecurityHeaders
Adds security headers to all responses:
- X-Frame-Options
- X-Content-Type-Options
- X-XSS-Protection
- Referrer-Policy
- Permissions-Policy
- Strict-Transport-Security (production only)
```php
// Register in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\SecurityHeaders::class);
})
```
## API Routes Template
An example API routes file is provided at `src/routes/api.example.php`.
Key patterns:
- Health check endpoint
- Protected routes with `auth:sanctum`
- Token management endpoints
- API versioning structure
## CORS Configuration
If your API is consumed by a separate frontend:
1. Copy `src/config/cors.php.example` to `config/cors.php`
2. Update `allowed_origins` with your frontend URL
3. Set `FRONTEND_URL` in `.env`
```env
FRONTEND_URL=https://your-frontend.com
```
## Development Workflow
### After Setup
```bash
# Start development
make up DB=mysql
# Run migrations
make artisan cmd='migrate'
# Create a user (tinker)
make tinker
# User::factory()->create(['email' => 'test@example.com'])
# Run tests
make test
# Fix code style
make lint
```
### Common Tasks
```bash
# Create controller
make artisan cmd='make:controller Api/PostController --api'
# Create model with migration
make artisan cmd='make:model Post -m'
# Create form request
make artisan cmd='make:request StorePostRequest'
# Create resource
make artisan cmd='make:resource PostResource'
# Create policy
make artisan cmd='make:policy PostPolicy --model=Post'
```
## Testing API
### With curl
```bash
# Register (if using Breeze API)
curl -X POST http://localhost:8080/api/register \
-H "Content-Type: application/json" \
-d '{"name":"Test","email":"test@test.com","password":"password","password_confirmation":"password"}'
# Login
curl -X POST http://localhost:8080/api/login \
-H "Content-Type: application/json" \
-d '{"email":"test@test.com","password":"password"}'
# Use token
curl http://localhost:8080/api/user \
-H "Authorization: Bearer YOUR_TOKEN"
```
### With Postman/Insomnia
1. Import the API collection (create from routes)
2. Set base URL to `http://localhost:8080/api`
3. Add Authorization header with Bearer token
## Troubleshooting
### CORS Errors
1. Check `config/cors.php` includes your frontend origin
2. Ensure `supports_credentials` is `true` if using cookies
3. Clear config cache: `php artisan config:clear`
### 401 Unauthorized
1. Check token is valid and not expired
2. Ensure `auth:sanctum` middleware is applied
3. For SPA: ensure CSRF cookie is set
### Session Issues
1. Check `SESSION_DOMAIN` matches your domain
2. For subdomains, use `.yourdomain.com`
3. Ensure Redis is running for session storage