mcpField
L
laravel

laravel

github.com/rawveg開発4037 回インストール36 週間前に更新
リポジトリ

laravel について

PHP開発者向けのLaravel 12.x開発スキルです。アプリやAPIの開発に使える、ルーティング、データアクセス、認証、バックグラウンドジョブの実例と資料を備えています。

主な機能

  1. 01ルーティングとミドルウェアのパターン
  2. 02Eloquentモデルとクエリ
  3. 03マイグレーションとデータベースシーディング
  4. 04認証とAPI開発
  5. 05キュー、キャッシュ、イベント
  6. 06Artisanコマンドの例

活用シーン

  1. 01LaravelアプリやAPIの構築
  2. 02リレーションの設計とクエリの最適化
  3. 03認証とAPIトークンの追加
  4. 04Laravelのエラーや性能問題の調査

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/rawveg/skillsforge-marketplace --skill laravel

インストール後、Claude Code で/laravelを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

plugin.json
references/
index.md
other.md

詳細

Laravel スキル

ルーティング、Eloquent ORM、マイグレーション、認証、API 開発、最新の PHP パターンなど、Laravel 12.x の開発を包括的にサポートします。

このスキルを使用するタイミング

次の場合に、このスキルを使用してください。

  • Laravel アプリケーションまたは API を構築するとき
  • Eloquent モデル、リレーションシップ、クエリを扱うとき
  • 認証、認可、API トークンを設定するとき
  • データベースのマイグレーション、シーダー、ファクトリーを作成するとき
  • ミドルウェア、サービスプロバイダー、イベントを実装するとき
  • Laravel の組み込み機能(キュー、キャッシュ、バリデーションなど)を使用するとき
  • Laravel のエラーやパフォーマンスの問題をトラブルシューティングするとき
  • Laravel のベストプラクティスや規約に従うとき
  • Laravel Sanctum または Passport で RESTful API を実装するとき
  • Laravel Mix、Vite、またはフロントエンドアセットを扱うとき

クイックリファレンス

基本的なルーティング
// Basic routes
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);

// Route parameters
Route::get('/users/{id}', function ($id) {
    return User::find($id);
});

// Named routes
Route::get('/profile', ProfileController::class)->name('profile');

// Route groups with middleware
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::resource('posts', PostController::class);
});
Eloquent モデルの基本
// Define a model with relationships
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'user_id'];

    protected $casts = [
        'published_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}
データベースのマイグレーション
// Create a 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('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->text('content');
            $table->timestamp('published_at')->nullable();
            $table->timestamps();

            $table->index(['user_id', 'published_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
フォームバリデーション
// Controller validation
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|max:255',
        'content' => 'required',
        'email' => 'required|email|unique:users',
        'tags' => 'array|min:1',
        'tags.*' => 'string|max:50',
    ]);

    return Post::create($validated);
}

// Form Request validation
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title' => 'required|max:255',
            'content' => 'required|min:100',
        ];
    }
}
Eloquent クエリビルダー
// Common query patterns
// Eager loading to avoid N+1 queries
$posts = Post::with(['user', 'comments'])
    ->where('published_at', '<=', now())
    ->orderBy('published_at', 'desc')
    ->paginate(15);

// Conditional queries
$query = Post::query();

if ($request->has('search')) {
    $query->where('title', 'like', "%{$request->search}%");
}

if ($request->has('author')) {
    $query->whereHas('user', function ($q) use ($request) {
        $q->where('name', $request->author);
    });
}

$posts = $query->get();
API リソースコントローラー
namespace App\Http\Controllers\Api;

use App\Models\Post;
use App\Http\Resources\PostResource;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(
            Post::with('user')->latest()->paginate()
        );
    }

    public function store(Request $request)
    {
        $post = Post::create($request->validated());

        return new PostResource($post);
    }

    public function show(Post $post)
    {
        return new PostResource($post->load('user', 'comments'));
    }

    public function update(Request $request, Post $post)
    {
        $post->update($request->validated());

        return new PostResource($post);
    }
}
API リソース(トランスフォーマー)
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'excerpt' => $this->excerpt,
            'content' => $this->when($request->routeIs('posts.show'), $this->content),
            'author' => new UserResource($this->whenLoaded('user')),
            'comments_count' => $this->when($this->comments_count, $this->comments_count),
            'published_at' => $this->published_at?->toISOString(),
            'created_at' => $this->created_at->toISOString(),
        ];
    }
}
Sanctum による認証
// API token authentication setup
// In config/sanctum.php - configure stateful domains

// Issue tokens
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
}

// Login endpoint
public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (!Auth::attempt($credentials)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $token = $request->user()->createToken('api-token')->plainTextToken;

    return response()->json(['token' => $token]);
}

// Protect routes
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', fn(Request $r) => $r->user());
});
ジョブとキュー
// Create a job
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class ProcessVideo implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public function __construct(
        public Video $video
    ) {}

    public function handle(): void
    {
        // Process the video
        $this->video->process();
    }
}

// Dispatch jobs
ProcessVideo::dispatch($video);
ProcessVideo::dispatch($video)->onQueue('videos')->delay(now()->addMinutes(5));
サービスコンテナと依存性注入
// Bind services in AppServiceProvider
use App\Services\PaymentService;

public function register(): void
{
    $this->app->singleton(PaymentService::class, function ($app) {
        return new PaymentService(
            config('services.stripe.secret')
        );
    });
}

// Use dependency injection in controllers
public function __construct(
    protected PaymentService $payment
) {}

public function charge(Request $request)
{
    return $this->payment->charge(
        $request->user(),
        $request->amount
    );
}

リファレンスファイル

このスキルには、references/ に包括的なドキュメントが含まれています。

  • other.md - Laravel 12.x のインストールガイドとコアドキュメント

詳細については、リファレンスファイルを参照してください。

  • インストールと設定
  • フレームワークのアーキテクチャと概念
  • 高度な機能とパッケージ
  • デプロイと最適化

主な概念

MVC アーキテクチャ

Laravel は Model-View-Controller パターンに従います。

  • モデル:データベーステーブルを表す Eloquent ORM クラス
  • ビュー:HTML をレンダリングする Blade テンプレート
  • コントローラー:HTTP リクエストを処理し、レスポンスを返します
Eloquent ORM

Laravel の強力なデータベース抽象化レイヤーです。

  • アクティブレコードパターン:各モデルインスタンスはデータベースの行を表します
  • リレーションシップ:belongsTo、hasMany、belongsToMany、morphMany など
  • クエリビルダー:SQL クエリを構築するための流れるようなインターフェース
  • Eager Loading:with() を使って N+1 クエリ問題を防ぎます
ルーティング

アプリケーションのエンドポイントを定義します。

  • ルートメソッド:get、post、put、patch、delete
  • ルートパラメーター:必須の {id} と任意の {id?}
  • ルートグループ:ミドルウェア、プレフィックス、名前空間を共有します
  • リソースルート:RESTful ルートを自動生成します
ミドルウェア

HTTP リクエストをフィルタリングします。

  • 組み込み:auth、throttle、verified、signed
  • カスタム:独自のリクエスト/レスポンスフィルターを作成します
  • グローバル:すべてのルートに適用します
  • ルート固有:特定のルートまたはグループに適用します
サービスコンテナ

Laravel の依存性注入コンテナです。

  • 自動解決:コンストラクターで依存関係を型指定します
  • バインディング:クラスの実装を登録します
  • シングルトン:リクエスト間で単一のインスタンスを共有します
Artisan コマンド

Laravel の CLI ツールです。

php artisan make:model Post -mcr  # Create model, migration, controller, resource
php artisan migrate               # Run migrations
php artisan db:seed              # Seed database
php artisan queue:work           # Process queue jobs
php artisan optimize:clear       # Clear all caches

このスキルの活用

初心者向け

次の項目から始めましょう。

  1. インストール:Composer を使って Laravel をセットアップします
  2. ルーティング:routes/web.php で基本的なルート定義を学びます
  3. コントローラー:php artisan make:controller でコントローラーを作成します
  4. モデル:Eloquent の基本とリレーションシップを理解します
  5. マイグレーション:マイグレーションでデータベーススキーマを定義します
  6. Blade テンプレート:Laravel のテンプレートエンジンでビューを作成します
中級者向け

次の項目に取り組みましょう。

  • フォームリクエスト:専用クラスでバリデーションと認可を行います
  • API リソース:JSON レスポンス向けにモデルを変換します
  • 認証:Laravel Breeze または Sanctum で実装します
  • リレーションシップ:Eager Loading と複雑なリレーションシップを習得します
  • キュー:時間のかかるタスクをバックグラウンドジョブに委ねます
  • イベントとリスナー:アプリケーションロジックを疎結合にします
上級者向け

以下をご覧ください。

  • サービスプロバイダー:アプリケーションサービスを登録します
  • カスタムミドルウェア:再利用可能なリクエストフィルターを作成します
  • パッケージ開発:再利用可能な Laravel パッケージを構築します
  • テスト:PHPUnit で機能テストとユニットテストを作成します
  • パフォーマンス:クエリ、キャッシュ、応答時間を最適化します
  • デプロイ:CI/CD パイプラインと本番環境の最適化
ナビゲーションのヒント
  • よく使うコードパターンについては、クイックリファレンスを確認してください
  • 公式ドキュメント(https://laravel.com/docs/12.x)を参照してください
  • php artisan route:list を使って、登録済みのすべてのルートを表示してください
  • php artisan tinker を使って、対話形式でデバッグしてください
  • データベースのパフォーマンスをデバッグするには、クエリログを有効にしてください

よく使われるパターン

リポジトリパターン
interface PostRepositoryInterface
{
    public function all();
    public function find(int $id);
    public function create(array $data);
}

class PostRepository implements PostRepositoryInterface
{
    public function all()
    {
        return Post::with('user')->latest()->get();
    }

    public function find(int $id)
    {
        return Post::with('user', 'comments')->findOrFail($id);
    }
}
アクションクラス(単一責任)
class CreatePost
{
    public function execute(array $data): Post
    {
        return DB::transaction(function () use ($data) {
            $post = Post::create($data);
            $post->tags()->attach($data['tag_ids']);
            event(new PostCreated($post));
            return $post;
        });
    }
}
クエリスコープ
class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->where('published_at', '<=', now());
    }

    public function scopeByAuthor($query, User $user)
    {
        return $query->where('user_id', $user->id);
    }
}

// Usage
Post::published()->byAuthor($user)->get();

リソース

公式ドキュメント
コミュニティ
ツール
  • Laravel Telescope:デバッグと監視
  • Laravel Horizon:キューの監視
  • Laravel Debugbar:開発時のデバッグ
  • Laravel IDE Helper:IDE の自動補完

ベストプラクティス

  1. フォームリクエストを使用する:バリデーションロジックをコントローラーから分離します
  2. リレーションを一括読み込みする:N+1 クエリの問題を回避します
  3. リソースコントローラーを使用する:RESTful の規約に従います
  4. 型ヒント:PHP の型宣言を活用して、IDE のサポートを向上させます
  5. データベーストランザクション:関連するデータベース操作をトランザクションで囲みます
  6. キュージョブ:時間のかかる処理をバックグラウンドワーカーに委ねます
  7. クエリをキャッシュする:コストの高いデータベースクエリをキャッシュします
  8. API リソース:API 向けにデータを一貫した形式に変換します
  9. イベント:イベントとリスナーを使ってアプリケーションロジックの依存を分離します
  10. テスト:アプリケーションの重要なロジックに対するテストを作成します

注意事項

  • Laravel 12.x の実行には PHP 8.2 以上が必要です
  • 依存関係の管理には Composer を使用します
  • アセットのコンパイルには Vite が含まれています(Laravel Mix に代わるものです)
  • 複数のデータベースシステム(MySQL、PostgreSQL、SQLite、SQL Server)をサポートします
  • キュー、キャッシュ、セッション、ファイルストレージを標準でサポートします
  • ファーストパーティーパッケージ(Sanctum、Horizon、Telescope など)を含む優れたエコシステムを備えています

コメント