Logo Laravel

Laravel

Cộng đồng
Omar-Obando
laravel

Laravel PHP framework development patterns — Eloquent ORM with factories and relationships, Form Requests for validation, Service Container and dependency injection, API resources for JSON APIs, Blade templating, queue jobs with ShouldQueue, middleware layers, policy-based authorization, migrations, and artisan commands.

Add to TypingMind

Tổng quan

Nhà phát hànhOmar-Obando
Kho mãqwen-orchestrator
Tên kỹ nănglaravel
Sao
53
Bản fork
13
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được Omar-Obando công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Laravel trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/Omar-Obando/qwen-orchestrator/tree/main/skills/laravel
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Omar-Obando/qwen-orchestrator.git /tmp/qwen-orchestrator
mkdir -p .claude/skills
cp -r /tmp/qwen-orchestrator/skills/laravel .claude/skills/laravel
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Laravel trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Laravel ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Laravel với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Laravel Development Skill — PHP Framework Mastery

This skill provides comprehensive Laravel development patterns following convention-over-configuration principles, Eloquent-first data access, and enterprise-grade architecture.

Key Principles

  • Convention over Configuration: Follow Laravel naming conventions for zero-config discovery
  • Eloquent-First: Use ORM for all data access; raw SQL only for complex queries
  • Validation at the Edge: Form Requests validate before reaching controllers
  • Thin Controllers, Fat Models: Business logic in models and services, not controllers

Project Scaffolding

Model Creation (All-in-One)

bash
php artisan make:model Product -crR
# Creates: Model + Controller (resource) + Form Requests + API Resource
FlagCreates
-cController
-rResource controller (CRUD methods)
-RForm Requests (StoreRequest, UpdateRequest)
-mMigration
-fFactory
-sSeeder

Eloquent ORM

Relationships

php
class User extends Model
{
    // One-to-One
    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }

    // One-to-Many
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    // Inverse: belongsTo (on the child model)
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    // Many-to-Many (pivot table)
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class)
            ->withPivot('assigned_at')
            ->withTimestamps();
    }

    // Polymorphic
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    // Has-One-Through
    public function license(): HasOneThrough
    {
        return $this->hasOneThrough(License::class, Subscription::class);
    }
}

Eager Loading (Prevent N+1)

php
// BAD: N+1 query — one query per post to get author
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name; // N queries
}

// GOOD: Eager load with 2 queries total
$posts = Post::with('author', 'comments.user')->get();
foreach ($posts as $post) {
    echo $post->author->name; // No additional queries
}

// Conditional eager loading
$posts = Post::with(['comments' => function ($query) {
    $query->where('is_approved', true)->latest();
}])->get();

// Lazy eager loading (load only when needed)
$posts = Post::all();
if ($needComments) {
    $posts->load('comments');
}

Factories and Seeders

php
// database/factories/ProductFactory.php
class ProductFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->words(3, true),
            'sku' => fake()->unique()->ean8(),
            'price' => fake()->randomFloat(2, 5, 500),
            'description' => fake()->paragraphs(3, true),
            'is_active' => true,
            'category_id' => Category::factory(),
        ];
    }

    public function inactive(): static
    {
        return $this->state(fn (array $attributes) => [
            'is_active' => false,
        ]);
    }
}

// database/seeders/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        Category::factory(10)->create();
        Product::factory(100)
            ->has(Review::factory()->count(3))
            ->create();
    }
}

Scopes, Accessors, and Mutators

php
class Product extends Model
{
    // Query Scope
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeInStock(Builder $query): Builder
    {
        return $query->where('stock_count', '>', 0);
    }

    // Accessor (computed attribute)
    protected function formattedPrice(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) =>
                '$' . number_format($attributes['price'], 2),
        );
    }

    // Mutator (transform on set)
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower(trim($value)),
        );
    }

    // Casts
    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'is_active' => 'boolean',
            'metadata' => 'array',
            'published_at' => 'datetime',
            'tags' => 'collection',
        ];
    }
}

Form Requests (Validation at the Edge)

php
// php artisan make:request StoreProductRequest
class StoreProductRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Product::class);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'sku' => ['required', 'string', 'unique:products,sku'],
            'price' => ['required', 'numeric', 'min:0', 'max:999999.99'],
            'description' => ['nullable', 'string', 'max:5000'],
            'category_id' => ['required', 'exists:categories,id'],
            'is_active' => ['boolean'],
            'tags' => ['array'],
            'tags.*' => ['string', 'max:50'],
        ];
    }

    public function messages(): array
    {
        return [
            'sku.unique' => 'This SKU is already in use.',
            'price.max' => 'Price cannot exceed 999,999.99.',
        ];
    }

    // Prepare data before validation
    protected function prepareForValidation(): void
    {
        $this->merge([
            'sku' => strtoupper(trim($this->sku)),
        ]);
    }
}

Service Container and Dependency Injection

Automatic Injection

php
class ProductController extends Controller
{
    // Automatic resolution via constructor
    public function __construct(
        private readonly ProductRepository $products,
    ) {}

    // Automatic resolution via method
    public function show(Product $product): ProductResource
    {
        return new ProductResource($product);
    }
}

Binding

php
// AppServiceProvider.php
public function register(): void
{
    // Interface → Implementation
    $this->app->bind(
        PaymentGatewayInterface::class,
        StripeGateway::class
    );

    // Singleton (shared instance)
    $this->app->singleton(
        CacheService::class,
        fn () => new CacheService(config('cache.ttl'))
    );

    // Scoped (one per request cycle)
    $this->app->scoped(TenantManager::class);

    // Factory binding (new instance each time)
    $this->app->bind(ReportGenerator::class, function ($app) {
        return new ReportGenerator(
            $app->make(DataSource::class),
            $app->make(Formatter::class),
        );
    });
}

API Development

API Resources

php
class ProductResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'sku' => $this->sku,
            'price' => [
                'amount' => (float) $this->price,
                'currency' => 'USD',
                'formatted' => $this->formatted_price,
            ],
            'category' => new CategoryResource($this->whenLoaded('category')),
            'reviews_count' => $this->whenCounted('reviews'),
            'tags' => $this->whenLoaded('tags'),
            'created_at' => $this->created_at->toISOString(),
            'links' => [
                'self' => route('api.products.show', $this->id),
            ],
        ];
    }
}

// Collection with metadata
class ProductCollection extends ResourceCollection
{
    public function toArray(Request $request): array
    {
        return [
            'data' => $this->collection,
            'meta' => [
                'total' => $this->total(),
                'count' => $this->count(),
                'per_page' => $this->perPage(),
                'current_page' => $this->currentPage(),
            ],
        ];
    }
}

API Routes

php
// routes/api.php
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::apiResource('products', ProductController::class);

    Route::get('products/search', [ProductController::class, 'search']);

    Route::prefix('admin')->middleware('role:admin')->group(function () {
        Route::apiResource('users', Admin\UserController::class);
    });
});

Queues and Jobs

Job Classes

php
class ProcessProductImport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 30;
    public bool $deleteWhenMissingModels = true;

    public function __construct(
        public readonly string $filePath,
        public readonly int $userId,
    ) {}

    public function handle(
        ProductImportService $importService,
        NotificationService $notifications,
    ): void {
        $result = $importService->import($this->filePath);

        $notifications->notifyUser($this->userId, new ImportComplete($result));
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('Product import failed', [
            'file' => $this->filePath,
            'error' => $exception->getMessage(),
        ]);
    }
}

// Dispatch
ProcessProductImport::dispatch($filePath, auth()->id())
    ->onQueue('imports')
    ->delay(now()->addMinutes(5));

// Job chains
Bus::chain([
    new ValidateImportFile($path),
    new ProcessProductImport($path),
    new CleanupImportFile($path),
])->catch(function (\Throwable $e) {
    Log::error('Import chain failed: ' . $e->getMessage());
})->dispatch();

Middleware

php
// Custom middleware
class EnsureTenantScope
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($tenant = $request->route('tenant')) {
            app(TenantManager::class)->setCurrent($tenant);
        }

        return $next($request);
    }
}

// Registration in bootstrap/app.php or Kernel.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->appendToGroup('api', [
        \App\Http\Middleware\EnsureJsonResponse::class,
    ]);

    $middleware->alias([
        'tenant' => \App\Http\Middleware\EnsureTenantScope::class,
        'role' => \App\Http\Middleware\EnsureRole::class,
    ]);
});

Policy-Based Authorization

php
// php artisan make:policy ProductPolicy --model=Product
class ProductPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->can('products.view');
    }

    public function view(User $user, Product $product): bool
    {
        return $user->belongsToTenant($product->tenant);
    }

    public function create(User $user): bool
    {
        return $user->can('products.create');
    }

    public function update(User $user, Product $product): bool
    {
        return $user->can('products.update')
            && $user->belongsToTenant($product->tenant);
    }

    // Super-admin bypass
    public function before(User $user, string $ability): bool|null
    {
        return $user->isSuperAdmin() ? true : null;
    }
}

// Usage in controller
class ProductController extends Controller
{
    public function update(UpdateProductRequest $request, Product $product)
    {
        $this->authorize('update', $product);
        // ...
    }
}

// Usage in Blade
@can('update', $product)
    <a href="{{ route('products.edit', $product) }}">Edit</a>
@endcan

Migrations

php
// php artisan make:migration create_products_table
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id')->nullable()->constrained()->nullOnDelete();
            $table->string('name');
            $table->string('sku')->unique();
            $table->decimal('price', 10, 2)->default(0);
            $table->text('description')->nullable();
            $table->json('metadata')->nullable();
            $table->boolean('is_active')->default(true);
            $table->unsignedInteger('stock_count')->default(0);
            $table->timestamp('published_at')->nullable();
            $table->softDeletes();
            $table->timestamps();

            // Indexes for common queries
            $table->index(['tenant_id', 'is_active']);
            $table->index('published_at');
            $table->fullText(['name', 'description']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Testing

Feature Tests with Pest

php
test('can list active products', function () {
    Product::factory(3)->create(['is_active' => true]);
    Product::factory(2)->create(['is_active' => false]);

    $response = $this->getJson('/api/products');

    $response->assertOk()
        ->assertJsonCount(3, 'data')
        ->assertJsonStructure([
            'data' => [
                '*' => ['id', 'name', 'price', 'category'],
            ],
        ]);
});

test('cannot create product without authentication', function () {
    $this->postJson('/api/products', [
        'name' => 'Test Product',
    ])->assertUnauthorized();
});

test('product belongs to user tenant', function () {
    $user = User::factory()->create();
    $product = Product::factory()->create(['tenant_id' => $user->tenant_id]);

    $response = $this->actingAs($user)
        ->getJson("/api/products/{$product->id}");

    $response->assertOk();
});

HTTP Test Assertions

php
$response->assertStatus(200);
$response->assertJson(['status' => 'success']);
$response->assertJsonPath('data.name', 'Test Product');
$response->assertJsonCount(10, 'data');
$response->assertJsonStructure(['data' => ['id', 'name']]);
$response->assertJsonValidationErrors(['email']);
$response->assertCreated();
$response->assertNotFound();
$response->assertForbidden();

Anti-Patterns

Anti-PatternProblemFix
Fat controllersHard to test, mixed concernsExtract to services/actions
Queries in Blade templatesN+1, slow renderingEager load in controller
No eager loadingN+1 queriesUse ::with() or ::load()
Raw SQL without bindingsSQL injectionUse Eloquent or parameterized queries
Ignoring mass assignmentSecurity vulnerabilityUse $fillable or $guarded on all models
Validation in controllersRepeated, hard to testUse Form Request classes
Business logic in routesNo reusabilityMove to controller or service
Not using database transactionsData inconsistencyWrap related operations in DB::transaction
Returning models directly from APIExposes internal structureUse API Resources for transformation
Catching all exceptions silentlyHidden bugsLog and handle specifically

When NOT to Use

Do NOT use this skill when:

  • Writing application business logic (use domain-driven skill)
  • Designing database schemas (use database-design skill)
  • Writing API endpoint implementations (use api-design skill)
  • Reviewing code for quality issues (use code-review skill)
  • Performing security audits (use security-auditor skill)
  • Analyzing deployment configurations (use deployment skill)
  • Writing SQL queries (use sql-best-practices skill)
  • Designing multi-page website layouts (use design-system skill)

Câu hỏi thường gặp

Kỹ năng AI Laravel làm được gì?

Laravel PHP framework development patterns — Eloquent ORM with factories and relationships, Form Requests for validation, Service Container and dependency injection, API resources for JSON APIs, Blade templating, queue jobs with ShouldQueue, middleware layers, policy-based authorization, migrations, and artisan commands.

Vì sao nên dùng Laravel trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Laravel là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Laravel trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/Omar-Obando/qwen-orchestrator/tree/main/skills/laravel. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Laravel?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Laravel với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Laravel với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Laravel có miễn phí không?

Có. Kỹ năng này được Omar-Obando phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇