home / skills / doanchienthangdev / omgkit / laravel

This skill helps you build Laravel APIs efficiently by guiding models, controllers, resources, auth, and queues with best practices.

npx playbooks add skill doanchienthangdev/omgkit --skill laravel

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
4.5 KB
---
name: building-laravel-apis
description: Builds enterprise Laravel applications with Eloquent, API Resources, Sanctum auth, and queue processing. Use when creating PHP backends, REST APIs, or full-stack Laravel applications.
---

# Laravel

## Quick Start

```php
// routes/api.php
Route::get('/health', fn () => ['status' => 'ok']);

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

## Features

| Feature | Description | Guide |
|---------|-------------|-------|
| Models | Eloquent ORM, relationships, scopes | [MODELS.md](MODELS.md) |
| Controllers | Resource controllers, form requests | [CONTROLLERS.md](CONTROLLERS.md) |
| API Resources | Response transformation | [RESOURCES.md](RESOURCES.md) |
| Auth | Sanctum, policies, gates | [AUTH.md](AUTH.md) |
| Queues | Jobs, events, listeners | [QUEUES.md](QUEUES.md) |
| Testing | Feature, unit tests | [TESTING.md](TESTING.md) |

## Common Patterns

### Model with Relationships

```php
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, SoftDeletes;

    protected $fillable = ['name', 'email', 'password', 'role'];
    protected $hidden = ['password', 'remember_token'];
    protected $casts = ['email_verified_at' => 'datetime', 'password' => 'hashed'];

    public function organizations(): BelongsToMany
    {
        return $this->belongsToMany(Organization::class, 'memberships')
            ->withPivot('role')
            ->withTimestamps();
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeSearch($query, ?string $search)
    {
        return $search
            ? $query->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
            : $query;
    }
}
```

### Controller with Service

```php
class UserController extends Controller
{
    public function __construct(private UserService $userService) {}

    public function index(Request $request): PaginatedCollection
    {
        $users = $this->userService->list(
            search: $request->input('search'),
            perPage: $request->input('per_page', 20)
        );
        return new PaginatedCollection($users, UserResource::class);
    }

    public function store(CreateUserRequest $request): JsonResponse
    {
        $user = $this->userService->create($request->validated());
        return (new UserResource($user))
            ->response()
            ->setStatusCode(201);
    }

    public function show(User $user): UserResource
    {
        return new UserResource($user->load('organizations'));
    }
}
```

### Form Request Validation

```php
class CreateUserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->isAdmin();
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:100'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
            'role' => ['sometimes', 'in:admin,user,guest'],
        ];
    }
}
```

## Workflows

### API Development

1. Create model and migration
2. Create controller with `php artisan make:controller --api`
3. Add Form Request for validation
4. Create API Resource for responses
5. Write feature tests

### Resource Response

```php
class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'organizations' => OrganizationResource::collection($this->whenLoaded('organizations')),
            'created_at' => $this->created_at->toIso8601String(),
        ];
    }
}
```

## Best Practices

| Do | Avoid |
|----|-------|
| Use Form Requests for validation | Validating in controllers |
| Use API Resources for responses | Returning models directly |
| Use service classes for logic | Fat controllers |
| Use eager loading | N+1 queries |
| Use soft deletes | Hard deletes for important data |

## Project Structure

```
app/
├── Http/
│   ├── Controllers/Api/
│   ├── Requests/
│   ├── Resources/
│   └── Middleware/
├── Models/
├── Services/
├── Policies/
├── Jobs/
└── Events/
routes/
├── api.php
└── web.php
tests/
├── Feature/
└── Unit/
```

For detailed examples and patterns, see reference files above.

Overview

This skill builds production-ready Laravel APIs and full-stack backends using Eloquent, API Resources, Sanctum authentication, and queue processing. It provides repeatable patterns for models, resource controllers, form requests, services, and tests to accelerate enterprise PHP projects. The kit favors service classes, validation via Form Requests, and API Resources for consistent responses.

How this skill works

The skill scaffolds routes, controllers, models, resources, and jobs following Laravel best practices. It wires Sanctum for token-based auth, uses Eloquent relationships and scopes for data modeling, and converts results to JSON through API Resources. Queues handle background jobs and listeners, while Form Requests centralize validation and authorization. Tests are organized into feature and unit suites to protect behavior.

When to use it

  • Building REST APIs or JSON backends for web and mobile clients
  • Creating multi-tenant or organization-based user models with relationships
  • Implementing token-based auth and per-client access with Sanctum
  • Moving heavy or long-running tasks to background processing with queues
  • Standardizing response shapes and pagination across endpoints

Best practices

  • Validate input with Form Requests and keep controllers thin by delegating logic to service classes
  • Transform responses with API Resources instead of returning models directly
  • Eager load relationships and use scopes to avoid N+1 queries
  • Protect endpoints with Sanctum plus policies/gates for fine-grained authorization
  • Use soft deletes for recoverable data and write feature tests for critical flows

Example use cases

  • User management API with registration, role-based access, and organization memberships
  • Paginated admin endpoints that return consistent resource shapes and metadata
  • Background email delivery or CSV exports using queued Jobs and Listeners
  • Secure mobile API authenticated by Sanctum tokens and guarded routes
  • Searchable endpoints with scope-based filtering and per-page controls

FAQ

How are requests validated?

Validation and authorization live in Form Request classes that are injected into controller actions for clear, reusable rules.

How does authentication work?

Sanctum issues tokens for clients and protects routes via the auth:sanctum middleware; policies and gates provide object-level authorization.