laravel-patterns

Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.

144,923 stars
Complexity: easy

About this skill

This skill equips an AI agent with comprehensive knowledge of production-ready Laravel architecture patterns, empowering it to design and develop robust web applications and APIs. It covers essential areas such as structuring routing and controllers, efficient use of Eloquent ORM, implementing service layers for business logic, managing background tasks with queues and events, optimizing performance with caching, and designing effective API resources with pagination. By leveraging these patterns, the AI agent can generate or evaluate code that adheres to industry best practices, ensuring scalability, maintainability, and high performance for complex Laravel projects.

Best use case

Designing and developing scalable Laravel applications, structuring application logic, optimizing database interactions, implementing background processes, and building robust APIs.

Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.

The AI agent will provide well-structured, production-grade Laravel code examples, architectural recommendations, or refactoring suggestions that align with established best practices for scalability, maintainability, and performance.

Practical example

Example input

Design a RESTful API for an e-commerce platform using Laravel. Include patterns for product management, user authentication, order processing, and efficient handling of large datasets. Focus on using service layers, API resources, queues for background tasks, and caching where appropriate.

Example output

To design a scalable RESTful API for an e-commerce platform in Laravel, we'll employ several architectural patterns:

1.  **Routing & Controllers**: Define API routes using `api.php` with resource controllers for `products`, `users`, `orders`, etc. Controllers will be lean, delegating business logic to service layers.
    Example: `Route::apiResource('products', ProductController::class);`

2.  **Service Layers (Actions/Services)**: Extract complex business logic from controllers into dedicated service classes or action classes. This promotes separation of concerns and testability.
    Example: `app/Services/ProductService.php` with methods like `createProduct(array $data)` or `updateProduct(Product $product, array $data)`. The controller would then call `$this->productService->createProduct($request->validated());`

3.  **Eloquent ORM & Relationships**: Define models (`Product`, `User`, `Order`, `Category`) with appropriate relationships (e.g., `Product hasMany OrderItems`, `User hasMany Order`). Utilize Eloquent features like eager loading (`with()`) for performance and query optimization.

4.  **API Resources**: Transform Eloquent models into a consistent API response format using Laravel API Resources. This ensures data consistency, allows for easy inclusion of relationships, and simplifies data transformation.
    Example: `return ProductResource::collection($products->paginate(15));`

5.  **Queues**: Use queues for time-consuming operations that don't require an immediate response, such as sending order confirmation emails, processing image uploads, or generating reports, improving user experience.
    Example: `SendOrderConfirmationEmail::dispatch($order)->onQueue('emails');`

6.  **Events & Listeners**: Decouple application components using events. For instance, an `OrderPlaced` event can trigger listeners for inventory update, notification, and analytics, promoting a loosely coupled architecture.
    Example: `event(new OrderPlaced($order));`

7.  **Caching**: Implement caching for frequently accessed, slow-to-change data like product categories or configuration settings to reduce database load and improve response times.
    Example: `Cache::remember('product_categories', 3600, fn() => Category::all());`

8.  **Error Handling**: Centralize API error handling using `app/Exceptions/Handler.php` to return consistent JSON error responses, improving API usability and debuggability.

This structured approach ensures the API is scalable, maintainable, and performs efficiently under load, adhering to best practices for production-grade Laravel applications.

When to use this skill

  • When building new Laravel web applications or APIs that require scalability and maintainability.
  • When refactoring existing Laravel projects to improve architecture and performance.
  • When structuring complex application logic using controllers, services, and domain models.
  • When working with Eloquent models, relationships, and advanced database operations.

When not to use this skill

  • For non-Laravel projects or frameworks.
  • For very small, simple CRUD applications where advanced architectural patterns might introduce unnecessary overhead.
  • When the primary goal is basic syntax generation without focusing on best practices or scalability.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/laravel-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/affaan-m/everything-claude-code/main/docs/tr/skills/laravel-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/laravel-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How laravel-patterns Compares

Feature / Agentlaravel-patternsStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Laravel Geliştirme Desenleri

Ölçeklenebilir, bakım yapılabilir uygulamalar için üretim seviyesi Laravel mimari desenleri.

## Ne Zaman Kullanılır

- Laravel web uygulamaları veya API'ler oluşturma
- Controller'lar, servisler ve domain mantığını yapılandırma
- Eloquent model'ler ve ilişkiler ile çalışma
- Resource'lar ve sayfalama ile API tasarlama
- Kuyruklar, event'ler, caching ve arka plan işleri ekleme

## Nasıl Çalışır

- Uygulamayı net sınırlar etrafında yapılandırın (controller'lar -> servisler/action'lar -> model'ler).
- Routing'i öngörülebilir tutmak için açık binding'ler ve scoped binding'ler kullanın; erişim kontrolü için yetkilendirmeyi yine de uygulayın.
- Domain mantığını tutarlı tutmak için typed model'leri, cast'leri ve scope'ları tercih edin.
- IO-ağır işleri kuyruklarda tutun ve pahalı okumaları önbelleğe alın.
- Config'i `config/*` içinde merkezileştirin ve ortamları açık tutun.

## Örnekler

### Proje Yapısı

Net katman sınırları (HTTP, servisler/action'lar, model'ler) ile geleneksel bir Laravel düzeni kullanın.

### Önerilen Düzen

```
app/
├── Actions/            # Tek amaçlı kullanım durumları
├── Console/
├── Events/
├── Exceptions/
├── Http/
│   ├── Controllers/
│   ├── Middleware/
│   ├── Requests/       # Form request validation
│   └── Resources/      # API resources
├── Jobs/
├── Models/
├── Policies/
├── Providers/
├── Services/           # Domain servislerini koordine etme
└── Support/
config/
database/
├── factories/
├── migrations/
└── seeders/
resources/
├── views/
└── lang/
routes/
├── api.php
├── web.php
└── console.php
```

### Controllers -> Services -> Actions

Controller'ları ince tutun. Orkestrasyon'u servislere ve tek amaçlı mantığı action'lara koyun.

```php
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 ve Controllers

Netlik için route-model binding ve resource controller'ları tercih edin.

```php
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('projects', ProjectController::class);
});
```

### Route Model Binding (Scoped)

Çapraz kiracı erişimini önlemek için scoped binding'leri kullanın.

```php
Route::scopeBindings()->group(function () {
    Route::get('/accounts/{account}/projects/{project}', [ProjectController::class, 'show']);
});
```

### İç İçe Route'lar ve Binding İsimleri

- Çift iç içe geçmeyi önlemek için prefix'leri ve path'leri tutarlı tutun (örn. `conversation` vs `conversations`).
- Bound model'e uyan tek bir parametre ismi kullanın (örn. `Conversation` için `{conversation}`).
- İç içe geçirirken üst-alt ilişkilerini zorlamak için scoped binding'leri tercih edin.

```php
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');
    });
});
```

Bir parametrenin farklı bir model sınıfına çözümlenmesini istiyorsanız, açık binding tanımlayın. Özel binding mantığı için `Route::bind()` kullanın veya model'de `resolveRouteBinding()` uygulayın.

```php
use App\Models\AiConversation;
use Illuminate\Support\Facades\Route;

Route::model('conversation', AiConversation::class);
```

### Service Container Binding'leri

Net bağımlılık bağlantısı için bir service provider'da interface'leri implementasyonlara bağlayın.

```php
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 Desenleri

### Model Yapılandırması

```php
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');
    }
}
```

### Özel Cast'ler ve Value Object'ler

Sıkı tiplemeler için enum'lar veya value object'leri kullanın.

```php
use Illuminate\Database\Eloquent\Casts\Attribute;

protected $casts = [
    'status' => ProjectStatus::class,
];
```

```php
protected function budgetCents(): Attribute
{
    return Attribute::make(
        get: fn (int $value) => Money::fromCents($value),
        set: fn (Money $money) => $money->toCents(),
    );
}
```

### N+1'i Önlemek için Eager Loading

```php
$orders = Order::query()
    ->with(['customer', 'items.product'])
    ->latest()
    ->paginate(25);
```

### Karmaşık Filtreler için Query Object'leri

```php
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 Scope'lar ve Soft Delete'ler

Varsayılan filtreleme için global scope'ları ve geri kurtarılabilir kayıtlar için `SoftDeletes` kullanın.
Katmanlı davranış istemediğiniz sürece, aynı filtre için global scope veya named scope kullanın, ikisini birden değil.

```php
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');
        });
    }
}
```

### Yeniden Kullanılabilir Filtreler için Query Scope'ları

```php
use Illuminate\Database\Eloquent\Builder;

final class Project extends Model
{
    public function scopeOwnedBy(Builder $query, int $userId): Builder
    {
        return $query->where('owner_id', $userId);
    }
}

// Servis, repository vb. içinde
$projects = Project::ownedBy($user->id)->get();
```

### Çok Adımlı Güncellemeler için Transaction'lar

```php
use Illuminate\Support\Facades\DB;

DB::transaction(function (): void {
    $order->update(['status' => 'paid']);
    $order->items()->update(['paid_at' => now()]);
});
```

### Migration'lar

### İsimlendirme Kuralı

- Dosya isimleri zaman damgası kullanır: `YYYY_MM_DD_HHMMSS_create_users_table.php`
- Migration'lar anonim sınıflar kullanır (isimlendirilmiş sınıf yok); dosya ismi amacı iletir
- Tablo isimleri varsayılan olarak `snake_case` ve çoğuldur

### Örnek Migration

```php
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 Request'ler ve Validation

Validation'ı form request'lerde tutun ve input'ları DTO'lara dönüştürün.

```php
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 Resource'ları

Resource'lar ve sayfalama ile API yanıtlarını tutarlı tutun.

```php
$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(),
    ],
]);
```

### Event'ler, Job'lar ve Kuyruklar

- Yan etkiler için domain event'leri yayınlayın (email'ler, analytics)
- Yavaş işler için kuyruğa alınmış job'ları kullanın (raporlar, export'lar, webhook'lar)
- Yeniden deneme ve backoff ile idempotent handler'ları tercih edin

### Caching

- Okuma-ağırlıklı endpoint'leri ve pahalı sorguları önbelleğe alın
- Model event'lerinde (created/updated/deleted) önbellekleri geçersiz kılın
- Kolay geçersiz kılma için ilgili verileri önbelleğe alırken tag'leri kullanın

### Yapılandırma ve Ortamlar

- Gizli bilgileri `.env`'de ve yapılandırmayı `config/*.php`'de tutun
- Ortama özel yapılandırma geçersiz kılmaları kullanın ve production'da `config:cache` kullanın

Related Skills

laravel-plugin-discovery

144923
from affaan-m/everything-claude-code

Discover and evaluate Laravel packages via LaraPlugins.io MCP. Use when the user wants to find plugins, check package health, or assess Laravel/PHP compatibility.

DevelopmentClaude

swiftui-patterns

144923
from affaan-m/everything-claude-code

SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。

DevelopmentClaude

perl-patterns

144923
from affaan-m/everything-claude-code

现代 Perl 5.36+ 的惯用法、最佳实践和约定,用于构建稳健、可维护的 Perl 应用程序。

DevelopmentClaude

kotlin-ktor-patterns

144923
from affaan-m/everything-claude-code

Ktor 服务器模式,包括路由 DSL、插件、身份验证、Koin DI、kotlinx.serialization、WebSockets 和 testApplication 测试。

DevelopmentClaude

kotlin-exposed-patterns

144923
from affaan-m/everything-claude-code

JetBrains Exposed ORM 模式,包括 DSL 查询、DAO 模式、事务、HikariCP 连接池、Flyway 迁移和仓库模式。

DevelopmentClaude

rust-patterns

144923
from affaan-m/everything-claude-code

Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.

DevelopmentClaude

laravel-verification

144923
from affaan-m/everything-claude-code

Verification loop for Laravel projects: env checks, linting, static analysis, tests with coverage, security scans, and deployment readiness.

DevelopmentClaude

laravel-tdd

144923
from affaan-m/everything-claude-code

Test-driven development for Laravel with PHPUnit and Pest, factories, database testing, fakes, and coverage targets.

DevelopmentClaude

laravel-security

144923
from affaan-m/everything-claude-code

Laravel security best practices for authn/authz, validation, CSRF, mass assignment, file uploads, secrets, rate limiting, and secure deployment.

DevelopmentClaude

springboot-patterns

144923
from affaan-m/everything-claude-code

Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.

DevelopmentClaude

jpa-patterns

144923
from affaan-m/everything-claude-code

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

DevelopmentClaude

django-patterns

144923
from affaan-m/everything-claude-code

Django architecture patterns, REST API design with DRF, ORM best practices, caching, signals, middleware, and production-grade Django apps.

DevelopmentClaude