Laravel
268 AI coding assistant skills, organized across 12 workflow layers. Sources include Anthropic official, FRM, SKC, LRN, SKA, and other mainstream AI coding frameworks.
npx -y skills add asong56/skills --skill laravelAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- 17 days oldThe repository was created 17 days ago. New is not bad, but a brand new repository carrying a familiar-sounding name is the shape a typosquat arrives in, and there has been no time for anyone else to find a problem with it.
- 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Complete Laravel skill: architecture patterns, REST API design, data access, and idiomatic Laravel code PLUS TDD workflow, security hardening, and full verification loop (build + lint + test + security scan). Incorporates former: laravel-patterns, laravel-quality.
SKILL.md
57.2 KB, as published. Nobody here has run it
Laravel Development Patterns
Production-grade Laravel architecture patterns for scalable, maintainable applications.
When to Use
- Building Laravel web applications or APIs
- Structuring controllers, services, and domain logic
- Working with Eloquent models and relationships
- Designing APIs with resources and pagination
- Adding queues, events, caching, and background jobs
How It Works
- Structure the app around clear boundaries (controllers -> services/actions -> models).
- Use explicit bindings and scoped bindings to keep routing predictable; still enforce authorization for access control.
- Favor typed models, casts, and scopes to keep domain logic consistent.
- Keep IO-heavy work in queues and cache expensive reads.
- Centralize config in
config/*and keep environments explicit.
Examples
Project Structure
Use a conventional Laravel layout with clear layer boundaries (HTTP, services/actions, models).
Recommended Layout
app/
├── Actions/ # Single-purpose use cases
├── Console/
├── Events/
├── Exceptions/
├── Http/
│ ├── Controllers/
│ ├── Middleware/
│ ├── Requests/ # Form request validation
│ └── Resources/ # API resources
├── Jobs/
├── Models/
├── Policies/
├── Providers/
├── Services/ # Coordinating domain services
└── Support/
config/
database/
├── factories/
├── migrations/
└── seeders/
resources/
├── views/
└── lang/
routes/
├── api.php
├── web.php
└── console.php
Controllers -> Services -> Actions
Keep controllers thin. Put orchestration in services and single-purpose logic in actions.
final class CreateOrderAction
{
public function __construct(private OrderRepository $orders) {}
public function handle(CreateOrderData $data): Order
{
return $this->orders->create($data);
}
}
final class OrdersController extends Controller
{
public function __construct(private CreateOrderAction $createOrder) {}
public function store(StoreOrderRequest $request): JsonResponse
{
$order = $this->createOrder->handle($request->toDto());
return response()->json([
'success' => true,
'data' => OrderResource::make($order),
'error' => null,
'meta' => null,
], 201);
}
}
Routing and Controllers
Prefer route-model binding and resource controllers for clarity.
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('projects', ProjectController::class);
});
Route Model Binding (Scoped)
Use scoped bindings to prevent cross-tenant access.
Route::scopeBindings()->group(function () {
Route::get('/accounts/{account}/projects/{project}', [ProjectController::class, 'show']);
});
Nested Routes and Binding Names
- Keep prefixes and paths consistent to avoid double nesting (e.g.,
conversationvsconversations). - Use a single parameter name that matches the bound model (e.g.,
{conversation}forConversation). - Prefer scoped bindings when nesting to enforce parent-child relationships.
use App\Http\Controllers\Api\ConversationController;
use App\Http\Controllers\Api\MessageController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->prefix('conversations')->group(function () {
Route::post('/', [ConversationController::class, 'store'])->name('conversations.store');
Route::scopeBindings()->group(function () {
Route::get('/{conversation}', [ConversationController::class, 'show'])
->name('conversations.show');
Route::post('/{conversation}/messages', [MessageController::class, 'store'])
->name('conversation-messages.store');
Route::get('/{conversation}/messages/{message}', [MessageController::class, 'show'])
->name('conversation-messages.show');
});
});
If you want a parameter to resolve to a different model class, define explicit binding. For custom binding logic, use Route::bind() or implement resolveRouteBinding() on the model.
use App\Models\AiConversation;
use Illuminate\Support\Facades\Route;
Route::model('conversation', AiConversation::class);
Service Container Bindings
Bind interfaces to implementations in a service provider for clear dependency wiring.
use App\Repositories\EloquentOrderRepository;
use App\Repositories\OrderRepository;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(OrderRepository::class, EloquentOrderRepository::class);
}
}
Eloquent Model Patterns
Model Configuration
final class Project extends Model
{
use HasFactory;
protected $fillable = ['name', 'owner_id', 'status'];
protected $casts = [
'status' => ProjectStatus::class,
'archived_at' => 'datetime',
];
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');
}
public function scopeActive(Builder $query): Builder
{
return $query->whereNull('archived_at');
}
}
Custom Casts and Value Objects
Use enums or value objects for strict typing.
use Illuminate\Database\Eloquent\Casts\Attribute;
protected $casts = [
'status' => ProjectStatus::class,
];
protected function budgetCents(): Attribute
{
return Attribute::make(
get: fn (int $value) => Money::fromCents($value),
set: fn (Money $money) => $money->toCents(),
);
}
Eager Loading to Avoid N+1
$orders = Order::query()
->with(['customer', 'items.product'])
->latest()
->paginate(25);
Query Objects for Complex Filters
final class ProjectQuery
{
public function __construct(private Builder $query) {}
public function ownedBy(int $userId): self
{
$query = clone $this->query;
return new self($query->where('owner_id', $userId));
}
public function active(): self
{
$query = clone $this->query;
return new self($query->whereNull('archived_at'));
}
public function builder(): Builder
{
return $this->query;
}
}
Global Scopes and Soft Deletes
Use global scopes for default filtering and SoftDeletes for recoverable records.
Use either a global scope or a named scope for the same filter, not both, unless you intend layered behavior.
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder;
final class Project extends Model
{
use SoftDeletes;
protected static function booted(): void
{
static::addGlobalScope('active', function (Builder $builder): void {
$builder->whereNull('archived_at');
});
}
}
Query Scopes for Reusable Filters
use Illuminate\Database\Eloquent\Builder;
final class Project extends Model
{
public function scopeOwnedBy(Builder $query, int $userId): Builder
{
return $query->where('owner_id', $userId);
}
}
// In service, repository etc.
$projects = Project::ownedBy($user->id)->get();
Transactions for Multi-Step Updates
use Illuminate\Support\Facades\DB;
DB::transaction(function (): void {
$order->update(['status' => 'paid']);
$order->items()->update(['paid_at' => now()]);
});
Migrations
Naming Convention
- File names use timestamps:
YYYY_MM_DD_HHMMSS_create_users_table.php - Migrations use anonymous classes (no named class); the filename communicates intent
- Table names are
snake_caseand plural by default
Example Migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table): void {
$table->id();
$table->foreignId('customer_id')->constrained()->cascadeOnDelete();
$table->string('status', 32)->index();
$table->unsignedInteger('total_cents');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('orders');
}
};
Form Requests and Validation
Keep validation in form requests and transform inputs to DTOs.
use App\Models\Order;
final class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->can('create', Order::class) ?? false;
}
public function rules(): array
{
return [
'customer_id' => ['required', 'integer', 'exists:customers,id'],
'items' => ['required', 'array', 'min:1'],
'items.*.sku' => ['required', 'string'],
'items.*.quantity' => ['required', 'integer', 'min:1'],
];
}
public function toDto(): CreateOrderData
{
return new CreateOrderData(
customerId: (int) $this->validated('customer_id'),
items: $this->validated('items'),
);
}
}
API Resources
Keep API responses consistent with resources and pagination.
$projects = Project::query()->active()->paginate(25);
return response()->json([
'success' => true,
'data' => ProjectResource::collection($projects->items()),
'error' => null,
'meta' => [
'page' => $projects->currentPage(),
'per_page' => $projects->perPage(),
'total' => $projects->total(),
],
]);
Events, Jobs, and Queues
- Emit domain events for side effects (emails, analytics)
- Use queued jobs for slow work (reports, exports, webhooks)
- Prefer idempotent handlers with retries and backoff
Caching
- Cache read-heavy endpoints and expensive queries
- Invalidate caches on model events (created/updated/deleted)
- Use tags when caching related data for easy invalidation
Configuration and Environments
- Keep secrets in
.envand config inconfig/*.php - Use per-environment config overrides and
config:cachein production
Quality Suite
Laravel Testing with TDD
Test-driven development for Laravel applications using PHPUnit, Pest, Laravel factories, and testing helpers.
When to use
- Writing new Laravel applications or features
- Implementing API endpoints with Sanctum or Passport authentication
- Testing Eloquent models, relationships, scopes, and accessors
- Setting up testing infrastructure for Laravel projects
- Writing feature tests for HTTP controllers and form requests
- Mocking external services (queues, mail, notifications, HTTP)
TDD Workflow for Laravel
Red-Green-Refactor Cycle
// Step 1: RED — Write a failing test
public function test_a_product_can_be_created(): void
{
$product = Product::factory()->create(['name' => 'Test Product']);
$this->assertDatabaseHas('products', ['name' => 'Test Product']);
}
// Step 2: GREEN — Write the migration, model, and factory
// Step 3: REFACTOR — Improve while keeping tests green
Setup
PHPUnit Configuration
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">tests/Feature</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
</php>
</phpunit>
Base TestCase Setup
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
protected function setUp(): void
{
parent::setUp();
// Call $this->withoutExceptionHandling() only in tests that
// test non-HTTP exceptions; it suppresses assertStatus() etc.
}
// Helper: Authenticate and return user
protected function actingAsUser(): mixed
{
$user = \App\Models\User::factory()->create();
$this->actingAs($user);
return $user;
}
protected function actingAsAdmin(): mixed
{
$admin = \App\Models\User::factory()->admin()->create();
$this->actingAs($admin);
return $admin;
}
}
Model Factories
// database/factories/UserFactory.php
class UserFactory extends Factory
{
protected static ?string $password = null;
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'role' => 'user',
];
}
public function admin(): static
{
return $this->state(fn (array $attributes) => ['role' => 'admin']);
}
public function unverified(): static
{
return $this->state(fn (array $attributes) => ['email_verified_at' => null]);
}
}
// database/factories/ProductFactory.php
class ProductFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->unique()->words(3, true),
'slug' => fn (array $attrs) => Str::slug($attrs['name']),
'description' => fake()->paragraph(),
'price' => fake()->numberBetween(100, 100000),
'stock' => fake()->numberBetween(0, 100),
'is_active' => true,
'user_id' => UserFactory::new(),
];
}
public function outOfStock(): static
{
return $this->state(fn (array $attributes) => ['stock' => 0]);
}
}
Using Factories
$user = User::factory()->create();
$admin = User::factory()->admin()->create();
$product = Product::factory()->create(['user_id' => $user->id]);
$products = Product::factory()->count(10)->create();
$draft = Product::factory()->make(); // Not persisted
// With relationships
$user = User::factory()->has(Product::factory()->count(3))->create();
// Sequences
User::factory()->count(3)->sequence(
['role' => 'admin'], ['role' => 'editor'], ['role' => 'user'],
)->create();
Model Testing
namespace Tests\Unit\Models;
use App\Models\User;
use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class UserTest extends TestCase
{
use RefreshDatabase;
public function test_it_hides_sensitive_attributes(): void
{
$user = User::factory()->create();
$this->assertArrayNotHasKey('password', $user->toArray());
}
public function test_admin_scope_returns_only_admins(): void
{
User::factory()->admin()->create();
User::factory()->count(3)->create();
$this->assertCount(1, User::admin()->get());
}
}
class ProductTest extends TestCase
{
use RefreshDatabase;
public function test_active_scope_filters_correctly(): void
{
Product::factory()->count(3)->create(['is_active' => true]);
Product::factory()->count(2)->create(['is_active' => false]);
$this->assertCount(3, Product::active()->get());
}
public function test_it_belongs_to_a_user(): void
{
$user = User::factory()->create();
$product = Product::factory()->create(['user_id' => $user->id]);
$this->assertTrue($product->user->is($user));
}
}
Feature / HTTP Testing
namespace Tests\Feature\Http\Controllers;
use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ProductControllerTest extends TestCase
{
use RefreshDatabase;
public function test_guests_are_redirected_to_login(): void
{
$this->get(route('products.create'))->assertRedirect(route('login'));
}
public function test_it_stores_a_new_product(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->post(route('products.store'), [
'name' => 'New Product',
'description' => 'Description',
'price' => 2999,
'stock' => 10,
]);
$response->assertRedirect(route('products.index'));
$this->assertDatabaseHas('products', [
'name' => 'New Product',
'user_id' => $user->id,
]);
}
public function test_it_validates_required_fields(): void
{
$this->actingAs(User::factory()->create());
$this->post(route('products.store'), [])
->assertSessionHasErrors(['name', 'price']);
}
public function test_users_cannot_modify_others_products(): void
{
$owner = User::factory()->create();
$attacker = User::factory()->create();
$product = Product::factory()->create(['user_id' => $owner->id]);
$this->actingAs($attacker)
->delete(route('products.destroy', $product))
->assertForbidden();
}
}
JSON API Testing
namespace Tests\Feature\Http\Controllers\Api;
use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ProductApiTest extends TestCase
{
use RefreshDatabase;
public function test_unauthenticated_requests_are_rejected(): void
{
$this->getJson('/api/products')->assertUnauthorized();
}
public function test_it_lists_paginated_products(): void
{
$user = User::factory()->create();
Product::factory()->count(5)->create(['user_id' => $user->id]);
$response = $this->actingAs($user)->getJson('/api/products');
$response->assertOk();
$response->assertJsonCount(5, 'data');
$response->assertJsonStructure([
'data' => [['id', 'name', 'price']],
'meta' => ['current_page', 'last_page', 'total'],
]);
}
public function test_it_creates_a_product(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->postJson('/api/products', [
'name' => 'API Product',
'price' => 4999,
]);
$response->assertCreated();
$response->assertJsonPath('data.name', 'API Product');
}
public function test_users_cannot_delete_others_products(): void
{
$owner = User::factory()->create();
$attacker = User::factory()->create();
$product = Product::factory()->create(['user_id' => $owner->id]);
$this->actingAs($attacker)
->deleteJson("/api/products/{$product->id}")
->assertForbidden();
}
}
Sanctum API Auth Testing
namespace Tests\Feature\Http\Controllers\Api;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class AuthControllerTest extends TestCase
{
use RefreshDatabase;
public function test_users_can_register(): void
{
$response = $this->postJson('/api/register', [
'name' => 'Test User',
'email' => '[email protected]',
'password' => 'Password123!',
'password_confirmation' => 'Password123!',
]);
$response->assertCreated();
$response->assertJsonStructure(['data' => ['user', 'token']]);
}
public function test_users_can_login(): void
{
User::factory()->create([
'email' => '[email protected]',
'password' => Hash::make('Password123!'),
]);
$response = $this->postJson('/api/login', [
'email' => '[email protected]',
'password' => 'Password123!',
]);
$response->assertOk();
$response->assertJsonStructure(['data' => ['token']]);
}
public function test_users_cannot_login_with_wrong_password(): void
{
User::factory()->create(['email' => '[email protected]']);
$this->postJson('/api/login', [
'email' => '[email protected]',
'password' => 'wrong',
])->assertUnprocessable();
}
public function test_token_bearer_authenticates_requests(): void
{
$user = User::factory()->create();
$token = $user->createToken('test')->plainTextToken;
$this->withToken($token)
->getJson('/api/user')
->assertOk()
->assertJsonPath('data.email', $user->email);
}
}
Mocking and Fakes
HTTP Fake
use Illuminate\Support\Facades\Http;
public function test_it_handles_successful_payment(): void
{
Http::fake([
'api.stripe.com/*' => Http::response(['id' => 'pi_123', 'status' => 'succeeded'], 200),
]);
$result = (new PaymentService())->charge(2999);
$this->assertTrue($result->success);
}
public function test_it_handles_gateway_failure(): void
{
Http::fake([
'api.stripe.com/*' => Http::response(['error' => 'card_declined'], 402),
]);
$this->expectException(PaymentFailedException::class);
(new PaymentService())->charge(2999);
}
public function test_it_retries_on_timeout(): void
{
Http::fake([
'api.stripe.com/*' => Http::sequence()
->pushStatus(408)
->pushStatus(200),
]);
$this->assertTrue((new PaymentService())->charge(2999)->success);
}
Mail Fake
Mail::fake();
$order->sendConfirmation();
Mail::assertSent(OrderConfirmation::class, function ($mail) use ($order) {
return $mail->hasTo($order->user->email);
});
Notification Fake
Notification::fake();
$user->notify(new WelcomeUser());
Notification::assertSentTo($user, WelcomeUser::class);
Queue Fake
Queue::fake();
ProcessImage::dispatch($product);
Queue::assertPushed(ProcessImage::class, function ($job) use ($product) {
return $job->product->id === $product->id;
});
Storage Fake
Storage::fake('public');
$file = UploadedFile::fake()->image('photo.jpg', 200, 200);
$response = $this->actingAs($user)->post('/avatar', [
'avatar' => $file,
]);
$response->assertSessionHasNoErrors();
Storage::disk('public')->assertExists('avatars/' . $file->hashName());
Event Fake
Event::fake();
$order->markAsShipped();
Event::assertDispatched(OrderShipped::class, function ($event) use ($order) {
return $event->order->id === $order->id;
});
Artisan Command Tests
public function test_it_sends_newsletters(): void
{
Mail::fake();
User::factory()->count(5)->create(['subscribed' => true]);
$this->artisan('newsletter:send')
->expectsOutput('Sending newsletter to 5 subscribers...')
->assertExitCode(0);
Mail::assertSent(NewsletterMail::class, 5);
}
public function test_it_handles_no_subscribers(): void
{
$this->artisan('newsletter:send')
->expectsOutput('No subscribers found.')
->assertExitCode(0);
}
Authorization Tests
public function test_users_can_update_own_posts(): void
{
$user = User::factory()->create();
$post = Post::factory()->create(['user_id' => $user->id]);
$this->actingAs($user)
->put(route('posts.update', $post), ['title' => 'Updated'])
->assertRedirect();
}
public function test_users_cannot_update_others_posts(): void
{
$post = Post::factory()->create();
$this->actingAs(User::factory()->create())
->put(route('posts.update', $post), ['title' => 'Hacked'])
->assertForbidden();
}
public function test_gate_before_grants_super_admin_full_access(): void
{
$super = User::factory()->create(['role' => 'super-admin']);
$post = Post::factory()->create();
$this->actingAs($super)
->delete(route('posts.destroy', $post))
->assertRedirect();
$this->assertSoftDeleted($post);
}
Pest Feature Tests
<?php
use App\Models\Product;
use App\Models\User;
uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->create();
$this->actingAs($this->user);
});
it('lists products', function () {
Product::factory()->count(3)->create(['user_id' => $this->user->id]);
$this->get(route('products.index'))
->assertOk()
->assertViewHas('products');
});
it('creates a product with valid data', function () {
$this->post(route('products.store'), [
'name' => 'Test Product', 'price' => 1999,
])->assertRedirect();
$this->assertDatabaseHas('products', ['name' => 'Test Product']);
});
it('fails validation without required fields', function () {
$this->post(route('products.store'), [])
->assertSessionHasErrors(['name', 'price']);
});
it('authorizes updates', function () {
$other = User::factory()->create();
$product = Product::factory()->create(['user_id' => $other->id]);
$this->put(route('products.update', $product), ['name' => 'Hacked'])
->assertForbidden();
});
Coverage
# PHPUnit (use clover output for CI threshold checks)
vendor/bin/phpunit --coverage-html coverage --coverage-clover clover.xml
# Pest (built-in threshold support)
vendor/bin/pest --coverage --min=80
Coverage Goals
| Component | Target |
|---|---|
| Models | 95%+ |
| Actions/Services | 90%+ |
| Form Requests | 90%+ |
| Controllers | 85%+ |
| Policies | 95%+ |
| Overall | 80%+ |
Testing Best Practices
DO
- Use factories over manual
create()calls - One logical assertion per test
- Descriptive names:
test_guests_cannot_create_products - Test edge cases and authorization boundaries
- Mock external services with
Http::fake(),Mail::fake() - Use
RefreshDatabasefor clean state
DON'T
- Don't test Laravel internals (trust the framework)
- Don't make tests dependent on each other
- Don't over-mock — mock only service boundaries
- Don't test private methods — test through the public interface
- Don't couple tests to HTML structure
Quick Reference
| Pattern | Usage |
|---|---|
RefreshDatabase | Reset database between tests |
$this->actingAs($user) | Authenticate as user |
$this->withToken($token) | Bearer token auth for APIs |
Model::factory()->create() | Create model with factory |
Model::factory()->count(5)->create() | Create multiple records |
Http::fake([...]) | Mock HTTP calls |
Mail::fake() | Trap sent mail |
Notification::fake() | Trap sent notifications |
Queue::fake() | Trap queued jobs |
Event::fake() | Trap dispatched events |
Storage::fake('public') | Trap file operations |
assertDatabaseHas | Assert DB row exists |
assertSoftDeleted | Assert soft-delete |
assertSessionHasErrors | Assert validation errors |
assertForbidden | Assert 403 status |
Related Skills
laravel-patterns— Laravel architecture, Eloquent, routing, and API patternslaravel-security— Laravel authentication, authorization, and secure codingtdd-workflow— The repo-wide RED -> GREEN -> REFACTOR loopbackend-patterns— General backend API and database patterns
Laravel Security
Laravel Security Best Practices
Comprehensive security guidelines for Laravel applications to protect against common vulnerabilities.
When to use
- Setting up Laravel authentication and authorization (Sanctum, Passport, Jetstream, Breeze)
- Implementing user roles, permissions, and policies
- Configuring production security settings and environment variables
- Reviewing Laravel applications for security vulnerabilities
- Deploying Laravel applications to production
- Writing secure Eloquent queries and migrations
Production Configuration
Essential Production Settings
// config/app.php
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false), // CRITICAL: Never true in production
'key' => env('APP_KEY'), // Must be set: php artisan key:generate
// config/session.php
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
// Verify APP_KEY is set at boot
// bootstrap/app.php or a service provider
if (empty(config('app.key'))) {
throw new RuntimeException('APP_KEY is not set. Run: php artisan key:generate');
}
Environment File Security
# NEVER commit .env to version control
# .gitignore already includes .env by default
# Use .env.example with placeholders instead
DB_PASSWORD=
APP_KEY=
SANCTUM_TOKEN_PREFIX=
# Validate required variables at boot
// In AppServiceProvider::boot()
$requiredKeys = ['app.key', 'database.connections.mysql.database', 'database.connections.mysql.username'];
foreach ($requiredKeys as $key) {
if (empty(config($key))) {
throw new RuntimeException("Missing required config key: {$key}");
}
}
HTTPS Enforcement
// AppServiceProvider::boot() or middleware
if (app()->environment('production')) {
URL::forceScheme('https');
request()->server->set('HTTPS', 'on');
}
// config/app.php for trusted proxies (load balancers)
// Use specific IP ranges — * trusts all, allowing X-Forwarded-* spoofing
// AWS: '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'
'trusted_proxies' => ['10.0.0.0/8', '172.16.0.0/12'],
// Force HTTPS in production via middleware
// app/Http/Middleware/ForceHttps.php
public function handle($request, Closure $next)
{
if (!$request->secure() && app()->environment('production')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
Authentication
Sanctum (API Token Authentication)
// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
)));
'expiration' => 60 * 24, // Token expiration in minutes (null = never)
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
// Issuing tokens with abilities
$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;
// Validate abilities on routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/orders', function () {
// User must have 'read' ability
abort_unless(Auth::user()->tokenCan('read'), 403);
// ...
})->middleware('abilities:read');
Route::post('/orders', function () {
// User must have 'write' ability
abort_unless(Auth::user()->tokenCan('write'), 403);
// ...
})->middleware('abilities:write');
});
Password Security
// config/hashing.php
// Default is bcrypt. Argon2id is stronger.
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12), // Increase for stronger hashing
],
'argon' => [
'memory' => 65536,
'threads' => 4,
'time' => 4,
],
// Password validation in RegisterRequest
public function rules(): array
{
return [
'password' => [
'required',
'confirmed',
Password::min(12)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised(), // Checks haveibeenpwned
],
];
}
// Rate limit login attempts
// App\Http\Controllers\Auth\AuthenticatedSessionController
protected function authenticated(Request $request, $user)
{
if ($user->wasRecentlyLockedOut()) {
// Notify user of suspicious login
$user->notify(new SuspiciousLoginNotification($request->ip()));
}
}
Session Management
// config/session.php
'driver' => env('SESSION_DRIVER', 'database'), // database/redis > file
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
'encrypt' => env('SESSION_ENCRYPT', false),
// Regenerate session on login
// App\Http\Controllers\Auth\AuthenticatedSessionController
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate(); // CRITICAL: prevents session fixation
return redirect()->intended(RouteServiceProvider::HOME);
}
// Invalidate session on logout
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
Authorization
Gates
// App\Providers\AuthServiceProvider
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
public function boot(): void
{
Gate::define('update-post', function (User $user, Post $post): bool {
return $user->id === $post->user_id;
});
Gate::define('publish-post', function (User $user): bool {
return $user->role === 'editor' || $user->role === 'admin';
});
// Using before() for super-admin override
Gate::before(function (User $user, string $ability): ?bool {
if ($user->role === 'super-admin') {
return true; // Grants all abilities
}
return null; // Fall through to normal checks
});
}
// Usage in controllers
public function update(Request $request, Post $post): RedirectResponse
{
Gate::authorize('update-post', $post);
// Or: $this->authorize('update-post', $post);
// Or: abort_unless(Auth::user()->can('update-post', $post), 403);
// ...
}
Policies
// App\Policies\PostPolicy
class PostPolicy
{
use HandlesAuthorization;
public function viewAny(?User $user): bool
{
return true; // Public listing
}
public function view(?User $user, Post $post): bool
{
return $post->is_published || ($user && $user->id === $post->user_id);
}
public function create(User $user): bool
{
return $user->hasVerifiedEmail(); // Must verify email first
}
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id && $post->created_at->diffInDays(now()) <= 30;
}
public function restore(User $user, Post $post): bool
{
return $user->role === 'admin';
}
public function forceDelete(User $user, Post $post): bool
{
return $user->role === 'super-admin';
}
}
// Register in AuthServiceProvider
protected $policies = [
Post::class => PostPolicy::class,
];
// Controller usage
public function show(Post $post): View
{
$this->authorize('view', $post);
return view('posts.show', compact('post'));
}
// Blade usage
@can('update', $post)
<a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan
@cannot('update', $post)
<span>You cannot edit this post</span>
@endcannot
Middleware Authorization
// Using middleware in routes
Route::put('/posts/{post}', [PostController::class, 'update'])
->middleware('can:update,post');
Route::get('/posts/create', [PostController::class, 'create'])
->middleware('can:create,App\Models\Post');
// Custom authorization middleware
// app/Http/Middleware/CheckRole.php
class CheckRole
{
public function handle(Request $request, Closure $next, string $role): mixed
{
if (!$request->user() || $request->user()->role !== $role) {
abort(403, 'Unauthorized. This area requires role: ' . $role);
}
return $next($request);
}
}
// Register in Kernel
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckRole::class,
];
// Route usage
Route::middleware(['auth', 'role:admin'])->group(function () {
Route::get('/admin', [AdminController::class, 'index']);
});
Eloquent Security
Mass Assignment Protection
// BAD: $guarded = [] allows ALL columns to be mass-assigned
// NEVER use $guarded = [] in production
// GOOD: Whitelist fillable attributes
final class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'phone',
'avatar',
];
// NEVER add 'role', 'is_admin', 'is_verified' here
}
// GOOD: Explicitly control which fields can be filled in requests
public function store(StoreUserRequest $request): RedirectResponse
{
$user = User::create($request->safe()->only([
'name', 'email', 'phone', 'avatar'
]));
// $request->safe() uses validated data only
// $request->only() is NOT safe on its own without validation rules
}
// BAD: Creating a user with request data directly
User::create($request->all()); // VULNERABLE to mass assignment!
// BETTER: Use DTOs for creation
$user = User::create($request->validated()); // Only validated fields
SQL Injection Prevention
// GOOD: Eloquent automatically parameterizes queries
User::where('email', $userInput)->first();
User::whereRaw('email = ?', [$userInput])->first();
// GOOD: Query Builder also parameterizes
DB::table('users')->where('email', $userInput)->first();
DB::select('SELECT * FROM users WHERE email = ?', [$userInput]);
// BAD: Raw string interpolation
DB::select("SELECT * FROM users WHERE email = '{$userInput}'"); // VULNERABLE!
User::whereRaw("email = '{$userInput}'")->first(); // VULNERABLE!
// BAD: whereRaw/orderByRaw with unescaped input
User::orderByRaw($userInput); // VULNERABLE!
User::groupByRaw($userInput); // VULNERABLE!
// BAD: DB::statement with concatenation
DB::statement("INSERT INTO users (email) VALUES ('{$userInput}')"); // VULNERABLE!
Attribute Casting
final class User extends Authenticatable
{
protected $casts = [
'email_verified_at' => 'datetime',
'is_admin' => 'boolean', // Cast to boolean prevents string injection
'settings' => 'array', // Automatically json_encode/json_decode
'metadata' => 'encrypted:array', // Laravel 11+ encrypted casting
'password' => 'hashed', // Laravel 10+ auto-hashes on set
];
}
Model Security
final class User extends Authenticatable
{
// Hide sensitive attributes from JSON/API responses
protected $hidden = [
'password',
'remember_token',
'two_factor_secret',
'two_factor_recovery_codes',
];
// Append only safe computed attributes
protected $appends = ['full_name']; // safe
// NEVER append sensitive computed data
}
final class Post extends Model
{
// Global scope to filter soft deleted records
use SoftDeletes;
// Prevent N+1 by restricting lazy loading (optional strict mode)
// AppServiceProvider::boot()
// Model::preventLazyLoading(!app()->isProduction());
}
CSRF Protection
Default Protection
// Laravel CSRF is enabled by default via VerifyCsrfToken middleware
// app/Http/Kernel.php (protected $middlewareGroups['web'])
// All POST/PUT/PATCH/DELETE forms must include @csrf
<form method="POST" action="/posts">
@csrf
<input type="text" name="title">
<button type="submit">Create</button>
</form>
Excluding Routes (Carefully)
// app/Http/Middleware/VerifyCsrfToken.php
class VerifyCsrfToken extends Middleware
{
// Only exclude routes that have external CSRF protection (webhooks, etc.)
protected $except = [
'stripe/*', // Stripe webhooks use their own signature verification
// Avoid blanket 'api/*' — stateful Sanctum routes need CSRF.
// Exclude only specific stateless webhook/endpoint routes.
];
}
CSRF with JavaScript
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
// Axios example (Laravel ships with Axios)
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector(
'meta[name="csrf-token"]'
).getAttribute('content');
// Fetch example
fetch('/posts', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
</script>
XSS Prevention
Blade Templating Security
{{-- SAFE: Auto-escaped by Blade --}}
{{ $userInput }}
{{-- DANGEROUS: Raw output — NEVER use with user input --}}
{!! $userInput !!}
{{-- SAFE: Only use {!! !!} with trusted content you control --}}
{!! $trustedHtmlFromYourServer !!}
{{-- GOOD: Use specific escaping directives --}}
@js($data) {{-- JSON encode for JavaScript --}}
@json($data) {{-- JSON encode in templates --}}
{{-- BAD: Direct user input in raw HTML --}}
<div>{!! $user->bio !!}</div> {{-- VULNERABLE if user provides bio --}}
Safe HTML Handling
// When you must allow some HTML, use a whitelist approach
use HTMLPurifier; // Requires: composer require ezyang/htmlpurifier
public function sanitizeHtml(string $dirty): string
{
$config = \HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,i,a[href],ul,ol,li,br');
$config->set('URI.AllowedSchemes', ['http', 'https', 'mailto']);
$purifier = new \HTMLPurifier($config);
return $purifier->purify($dirty);
}
// In blade:
<div>{!! $sanitizedContent !!}</div> {{-- Safe after purification --}}
JavaScript Context Escaping
{{-- SAFE: Blade @js escapes for JavaScript context --}}
<script>
const user = @js($user); // JSON + escaped for JS context
const settings = @json($settings); // Direct JSON encode
</script>
{{-- DANGEROUS: Manual JSON in JS context --}}
<script>
const user = {{ json_encode($user) }}; // NOT escaped for JS!
</script>
HTTP Headers for XSS Protection
// App\Http\Middleware\SecurityHeaders.php
class SecurityHeaders
{
public function handle(Request $request, Closure $next): mixed
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'"
);
return $response;
}
}
// Register in kernel
protected $middleware = [
\App\Http\Middleware\SecurityHeaders::class,
];
Input Validation
Form Request Validation
final class StorePostRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->can('create', Post::class) ?? false;
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255', 'sanitize_html'],
'content' => ['required', 'string', 'max:10000'],
'image' => [
'required',
'image',
'mimes:jpg,jpeg,png,gif,webp', // Whitelist specific types
'max:2048', // 2MB max
],
'tags' => ['array'],
'tags.*' => ['integer', 'exists:tags,id'],
];
}
public function messages(): array
{
return [
'title.max' => 'Post title must not exceed 255 characters.',
'image.max' => 'Image must be under 2MB.',
];
}
// Sanitize input after validation
public function validated($key = null, $default = null): mixed
{
$validated = parent::validated();
$validated['title'] = strip_tags($validated['title']);
return $key ? ($validated[$key] ?? $default) : $validated;
}
}
Custom Validation Rules
// app/Rules/StrongPassword.php
class StrongPassword implements Rule
{
public function passes($attribute, $value): bool
{
return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#^()_\-+=])[A-Za-z\d@$!%*?&#^()_\-+=]{12,}$/', $value);
}
public function message(): string
{
return 'The :attribute must be at least 12 characters with uppercase, lowercase, number, and symbol.';
}
}
// app/Rules/NotBlacklistedDomain.php
class NotBlacklistedDomain implements Rule
{
private array $blacklisted = ['mailinator.com', 'guerrillamail.com'];
public function passes($attribute, $value): bool
{
$domain = substr(strrchr($value, '@'), 1);
return !in_array(strtolower($domain), $this->blacklisted);
}
public function message(): string
{
return 'Email from disposable domains is not allowed.';
}
}
API Security
Rate Limiting
// App/Providers/RouteServiceProvider
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('auth', function (Request $request) {
return Limit::perMinute(5)->by($request->ip())
->response(function () {
return response()->json([
'message' => 'Too many login attempts. Try again in 1 minute.',
], 429);
});
});
RateLimiter::for('uploads', function (Request $request) {
return Limit::perHour(10)->by($request->user()?->id ?? $request->ip())
->response(function () {
return response()->json([
'message' => 'Upload limit reached. Try again later.',
], 429);
});
});
}
// Route usage
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
Route::apiResource('posts', PostController::class);
});
Route::post('/login', [AuthController::class, 'login'])
->middleware('throttle:auth');
API Authentication — Sanctum vs Passport
// Sanctum (recommended for most apps — simple, first-party, SPA)
// config/sanctum.php
'expiration' => 60 * 24, // Tokens expire after 24 hours
'model' => User::class,
// Issuing scoped tokens
$token = $user->createToken('client-name', [
'posts:read',
'posts:write',
])->plainTextToken;
// Middleware scoping
Route::middleware('auth:sanctum')->group(function () {
Route::get('/posts', [PostController::class, 'index'])
->middleware('abilities:posts:read');
Route::post('/posts', [PostController::class, 'store'])
->middleware('abilities:posts:write');
});
// Passport (OAuth2 — for third-party clients or complex auth flows)
// Install: composer require laravel/passport
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
CORS Configuration
// config/cors.php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => explode(',', env('CORS_ALLOWED_ORIGINS', '')), // Whitelist specific origins
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => ['X-Total-Count', 'X-Pagination-Page'],
'max_age' => 0,
'supports_credentials' => true, // Required for Sanctum SPA auth
];
// NEVER: Allow all origins in production unless absolutely necessary
// 'allowed_origins' => ['*'], // Only for truly public APIs
File Upload Security
Validation
public function rules(): array
{
return [
'document' => [
'required',
'file',
'mimes:pdf,doc,docx,xls,xlsx', // Whitelist specific MIME types
'max:10240', // 10MB
'extensions:pdf,doc,docx,xls,xlsx', // Verify extension matches MIME
],
'avatar' => [
'nullable',
'image', // Ensures it's a valid image
'mimes:jpg,jpeg,png,webp',
'max:2048',
'dimensions:min_width=100,min_height=100,max_width=2000,max_height=2000',
],
];
}
Secure Storage
// Store files outside public directory
$path = $request->file('document')->store('documents', 'local');
// Never use 'public' disk for sensitive documents
// Use signed URLs for temporary file access
use Illuminate\Support\Facades\Storage;
public function download(Request $request, string $path)
{
// Generate temporary signed URL (expires in 15 minutes)
$url = Storage::temporaryUrl($path, now()->addMinutes(15));
// Validate user has permission
$this->authorize('download', $path);
return redirect($url);
}
// Storage configuration for cloud with encryption
// config/filesystems.php
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'server_side_encryption' => 'AES256', // Encrypt at rest
],
Dependencies and Secrets
Composer Security
# Always audit dependencies in CI
composer audit
# Pin major versions in composer.json
"laravel/framework": "^11.0",
"spatie/laravel-permission": "^6.0"
# Check for abandoned packages
composer why-not
# Keep lock file in version control (it pins exact versions)
# Run `composer update` deliberately, never in CI/CD
Secret Management
# .env file (NEVER commit)
# .gitignore includes .env by default
APP_KEY=base64:abc123...
DB_PASSWORD=secure_password
STRIPE_KEY=sk_live_...
SANCTUM_TOKEN_PREFIX=myapp_
# For production: Use a secret manager
# Deploy with: env $(aws secretsmanager get-secret-value --secret-id prod/db | jq ...) php artisan serve
# Validate secrets at boot (AppServiceProvider::boot)
$secrets = ['services.stripe.key', 'services.stripe.webhook_secret'];
foreach ($secrets as $key) {
if (empty(config($key))) {
Log::critical("Missing secret: {$key}");
}
}
Queue Security
// Define a named rate limiter (typically in AppServiceProvider::boot())
RateLimiter::for('payments', fn () => Limit::perMinute(5));
// Encrypt sensitive job data by implementing the interface
final class ProcessPaymentJob implements ShouldQueue, ShouldBeEncrypted
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
private readonly string $paymentIntentId, // Public IDs are fine
private readonly string $cardFingerprint, // Encrypted via ShouldBeEncrypted
) {}
public function handle(): void
{
// Process payment
}
// Limit retries and delay between attempts
public function retryUntil(): Carbon
{
return now()->addMinutes(5);
}
// Rate limit how many jobs of this type can run
public function middleware(): array
{
return [
new RateLimited('payments'),
];
}
}
Logging Security Events
// config/logging.php
'channels' => [
'security' => [
'driver' => 'single',
'path' => storage_path('logs/security.log'),
'level' => 'warning',
],
],
// Audit log helper
final class SecurityLogger
{
public static function log(string $event, array $context = []): void
{
Log::channel('security')->warning($event, array_merge([
'user_id' => Auth::id(),
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
'url' => request()->fullUrl(),
'timestamp' => now()->toIso8601String(),
], $context));
}
}
// Usage
SecurityLogger::log('failed_login_attempt', ['email' => $email]);
SecurityLogger::log('password_change');
SecurityLogger::log('role_change', ['target_user' => $targetId, 'new_role' => 'admin']);
SecurityLogger::log('suspicious_activity', ['reason' => 'multiple_attempts_from_different_ips']);
Quick Security Checklist
| Check | Description |
|---|---|
APP_DEBUG=false | Never run with debug enabled in production |
APP_KEY set | Always run php artisan key:generate |
| HTTPS enforced | Force HTTPS in production via middleware or proxy |
$fillable whitelisted | Never use $guarded = [] |
| CSRF active | @csrf on all state-changing forms |
| Sanctum/Passport configured | API authentication with token abilities/scopes |
| Rate limiting applied | Throttle API and auth endpoints |
| Input validation | FormRequest with specific rules, never $request->all() |
| File upload restrictions | Validate MIME types, size, dimensions |
composer audit in CI | Check dependencies for known vulnerabilities |
password_hash / password_verify | Use Laravel's built-in hashing (bcrypt/Argon2) |
| Session regeneration on login | Call $request->session()->regenerate() |
| Security headers middleware | CSP, X-Frame-Options, X-Content-Type-Options |
| Logged security events | Audit log for auth failures, role changes, suspicious activity |
.env not committed | Verify .gitignore includes .env |
Related Skills
laravel-patterns— Laravel architecture, routing, Eloquent, and API patternsbackend-patterns— General backend API and database patternslaravel-tdd— Laravel testing with PHPUnit and Pest
Laravel Verification
Laravel Verification Loop
Run before PRs, after major changes, and pre-deploy.
When to Use
- Before opening a pull request for a Laravel project
- After major refactors or dependency upgrades
- Pre-deployment verification for staging or production
- Running full lint -> test -> security -> deploy readiness pipeline
How It Works
- Run phases sequentially from environment checks through deployment readiness so each layer builds on the last.
- Environment and Composer checks gate everything else; stop immediately if they fail.
- Linting/static analysis should be clean before running full tests and coverage.
- Security and migration reviews happen after tests so you verify behavior before data or release steps.
- Build/deploy readiness and queue/scheduler checks are final gates; any failure blocks release.
Phase 1: Environment Checks
php -v
composer --version
php artisan --version
- Verify
.envis present and required keys exist - Confirm
APP_DEBUG=falsefor production environments - Confirm
APP_ENVmatches the target deployment (production,staging)
If using Laravel Sail locally:
./vendor/bin/sail php -v
./vendor/bin/sail artisan --version
Phase 1.5: Composer and Autoload
composer validate
composer dump-autoload -o
Phase 2: Linting and Static Analysis
vendor/bin/pint --test
vendor/bin/phpstan analyse
If your project uses Psalm instead of PHPStan:
vendor/bin/psalm
Phase 3: Tests and Coverage
php artisan test
Coverage (CI):
XDEBUG_MODE=coverage php artisan test --coverage
CI example (format -> static analysis -> tests):
vendor/bin/pint --test
vendor/bin/phpstan analyse
XDEBUG_MODE=coverage php artisan test --coverage
Phase 4: Security and Dependency Checks
composer audit
Phase 5: Database and Migrations
php artisan migrate --pretend
php artisan migrate:status
- Review destructive migrations carefully
- Ensure migration filenames follow
Y_m_d_His_*(e.g.,2025_03_14_154210_create_orders_table.php) and describe the change clearly - Ensure rollbacks are possible
- Verify
down()methods and avoid irreversible data loss without explicit backups
Phase 6: Build and Deployment Readiness
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
- Ensure cache warmups succeed in production configuration
- Verify queue workers and scheduler are configured
- Confirm
storage/andbootstrap/cache/are writable in the target environment
Phase 7: Queue and Scheduler Checks
php artisan schedule:list
php artisan queue:failed
If Horizon is used:
php artisan horizon:status
If queue:monitor is available, use it to check backlog without processing jobs:
php artisan queue:monitor default --max=100
Active verification (staging only): dispatch a no-op job to a dedicated queue and run a single worker to process it (ensure a non-sync queue connection is configured).
php artisan tinker --execute="dispatch((new App\\Jobs\\QueueHealthcheck())->onQueue('healthcheck'))"
php artisan queue:work --once --queue=healthcheck
Verify the job produced the expected side effect (log entry, healthcheck table row, or metric).
Only run this on non-production environments where processing a test job is safe.
Examples
Minimal flow:
php -v
composer --version
php artisan --version
composer validate
vendor/bin/pint --test
vendor/bin/phpstan analyse
php artisan test
composer audit
php artisan migrate --pretend
php artisan config:cache
php artisan queue:failed
CI-style pipeline:
composer validate
composer dump-autoload -o
vendor/bin/pint --test
vendor/bin/phpstan analyse
XDEBUG_MODE=coverage php artisan test --coverage
composer audit
php artisan migrate --pretend
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan schedule:list