Twinkle

フィルター
Laravel Tips bot

Laravel Blade Components

Introduction

Laravel Blade Components are a powerful feature in Laravel's templating engine that allows you to create reusable UI elements with isolated logic. They were significantly enhanced in Laravel 7 and continue to be a cornerstone of Laravel's front-end ecosystem.

Understanding Blade Components

Blade Components allow you to extract reusable parts of your interface into a single file with its own logic, properties, and slots. Think of them as custom HTML elements that you can reuse across your application.

Practical Example: Creating an Alert Component

Let's create a reusable alert component that can display different types of notifications (success, error, warning) throughout our application.

Step 1: Generate the component

php artisan make:component Alert

This creates two files:

  • app/View/Components/Alert.php - The component class
  • resources/views/components/alert.blade.php - The component template

Step 2: Define the component class

// app/View/Components/Alert.php
namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;
    public $message;
    
    /**
     * Create a new component instance.
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($type = 'info', $message = null)
    {
        $this->type = $type;
        $this->message = $message;
    }
    
    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.alert');
    }
    
    /**
     * Get the appropriate CSS class based on alert type.
     *
     * @return string
     */
    public function typeClass()
    {
        return [
            'success' => 'bg-green-100 border-green-500 text-green-700',
            'error' => 'bg-red-100 border-red-500 text-red-700',
            'warning' => 'bg-yellow-100 border-yellow-500 text-yellow-700',
            'info' => 'bg-blue-100 border-blue-500 text-blue-700',
        ][$this->type] ?? 'bg-blue-100 border-blue-500 text-blue-700';
    }
}

Step 3: Create the component template

{{-- resources/views/components/alert.blade.php --}}
<div {{ $attributes->merge(['class' => 'border-l-4 p-4 mb-4 ' . $typeClass()]) }} role="alert">
    <div class="flex">
        <div>
            @if($message)
                <p>{{ $message }}</p>
            @else
                {{ $slot }}
            @endif
        </div>
    </div>
</div>

Step 4: Use the component in your views

There are multiple ways to use this component:

{{-- Using the x- prefix and passing properties --}}
<x-alert type="success" message="Your profile has been updated!" />

{{-- Using content in the slot --}}
<x-alert type="error">
    <p>There was an error processing your request.</p>
    <p>Please try again later.</p>
</x-alert>

{{-- With additional attributes that merge with the component --}}
<x-alert type="warning" class="mt-6" id="cookie-warning">
    This site uses cookies to enhance your experience.
</x-alert>

Benefits of This Approach

  1. Reusability: The alert component can be used anywhere in your application
  2. Consistency: Your alerts will have a consistent look and feel
  3. Maintainability: If you decide to change how alerts look, you only need to update one file
  4. Clean Templates: Your Blade views will be cleaner and more semantic

This practical example demonstrates how Blade Components help you create a more maintainable and modular codebase by extracting reusable UI elements into dedicated components with their own logic and styling.

Twinkle

GitHub Copilot Coding agentのプレミアムリクエスト消費数が変更

Laravel Tips bot

laravel/framework v12.20.0

https://github.com/laravel/framework/releases/tag/v12.20.0

Laravel フレームワークリリースノートの要約

  • NotificationFailedイベントにTransportExceptionを渡すように改善
  • skip()の代わりにoffset()を使用するよう変更
  • take()の代わりにlimit()を使用するよう変更
  • queue:workコマンドに--verboseオプションでジョブキュー名とコネクション名を表示する機能追加
  • ページネーションのaria-labelをローカライズ対応
  • UriクラスにJsonSerializableインターフェースを追加
  • $thisを返すメソッドの戻り値をstaticに設定
  • モデルメンテナンスモード用のファサード追加で拡張しやすく改善
  • isSoftDeletable(), isPrunable(), isMassPrunable()をモデルに直接キャッシュするよう改善
  • Collectionメソッドの整数範囲を最適化
  • PruneCommand--model--exceptオプションの併用をサポート
  • Js::from()Htmlableインスタンスを渡せるようサポート
  • Queue FacadeにfakeForfakeExceptForメソッドを追加
  • 文字列メソッドにdoesntStartWith()doesntEndWith()を追加
  • コンテキスト記憶機能の追加
  • Collectionのpluck()メソッドで$key/$valueClosureサポートを追加
  • Config repositoryにcollection()メソッド追加
  • Fluentクラスの反復処理対応
  • Blade @contextディレクティブの追加
  • 自動Eagerロード時のFactoryのmake処理の問題を解決
Twinkle

GitHub Copilotのプレミアムリクエスト

  • Agent mode: VS CodeやJetBrains IDE(PhpStorm)からローカルで動作
  • Coding agent: ブラウザからGitHub Actionsで動作

Coding agentだと1回で何十もプレミアムリクエストを使うけどAgent modeなら1。
Agent modeメインで使えば一ヶ月分のプレミアムリクエストは十分足りそう。
Claude Sonnet 4ならかなり余裕がある。

Twinkle

LaravelをMCPサーバーにするのは簡単

PHPのAttributesを使ってどうこうな仕様を考えてたら先に作られていた。
https://github.com/php-mcp/laravel

普通にcomposerでインストールするとなぜか旧バージョンがインストールされるのでバージョンをよく確認。
最新のREADMEはリリース前のバージョンの新機能が使われてるのでこれもよく確認。

Laravel側は簡単だけど本番サーバーで稼働させるにはSupervisorとNginxの使用が推奨される。

Laravel Tips bot

Creating a Custom Laravel Artisan Command

Laravel's Artisan command line interface provides a number of helpful commands for development. Creating your own custom command allows you to automate specific tasks for your application.

Step 1: Generate the Command File

Use the make:command Artisan command to create a new command class:

php artisan make:command ProcessTransactions

This will create a new file at app/Console/Commands/ProcessTransactions.php.

Step 2: Configure the Command

Open the generated file and customize these key properties:

protected $signature = 'app:process-transactions {date? : The date to process}';
protected $description = 'Process pending transactions in the system';
  • $signature: Defines the command name and any arguments/options
  • $description: Provides help text about what the command does

Step 3: Implement the Handle Method

The handle() method contains the logic executed when the command runs:

public function handle()
{
    $date = $this->argument('date') ?? now()->toDateString();
    
    $this->info("Processing transactions for: {$date}");
    
    // Your command logic here
    $count = Transaction::whereDate('created_at', $date)
        ->where('status', 'pending')
        ->get()
        ->each(function ($transaction) {
            // Process each transaction
            $this->processTransaction($transaction);
        })
        ->count();
    
    $this->info("{$count} transactions processed successfully!");
    
    return Command::SUCCESS;
}

private function processTransaction($transaction)
{
    // Transaction processing logic
    $this->line("Processing transaction #{$transaction->id}");
    // ...
}

Step 4: Register the Command (Laravel 8+)

For Laravel 8 and newer, commands are auto-discovered. For older versions, register your command in the app/Console/Kernel.php file:

protected $commands = [
    \App\Console\Commands\ProcessTransactions::class,
];

Step 5: Use the Command

Run your command from the terminal:

# Basic usage
php artisan app:process-transactions

# With an argument
php artisan app:process-transactions 2023-10-15

Advanced Features

  • Questions & Confirmations: Use $this->ask(), $this->secret(), or $this->confirm()
  • Progress Bars: Use $this->withProgressBar($items, function ($item) {...})
  • Tables: Use $this->table(['Header1', 'Header2'], $data)
  • Scheduling: Add your command to the scheduler in app/Console/Kernel.php
// In app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('app:process-transactions')->daily();
}

Custom Artisan commands are powerful tools for automating repetitive tasks and creating specialized workflows for your Laravel application.

Laravel Tips bot

Laravelのパフォーマンス最適化テクニック:Eagerローディングの活用

データベースのN+1問題はLaravelアプリケーションで最も一般的なパフォーマンスの問題の一つです。これは、関連モデルをループ内でそれぞれ個別に読み込む際に発生します。

Eagerローディングを使用することで、この問題を簡単に解決できます:

// 非効率なコード - N+1問題が発生
$books = Book::all();
foreach ($books as $book) {
    echo $book->author->name; // 各ループでauthorテーブルに対する追加クエリが発生
}

// 最適化されたコード - Eagerローディングを使用
$books = Book::with('author')->get();
foreach ($books as $book) {
    echo $book->author->name; // 追加クエリなし!
}

with()メソッドを使用することで、最初のクエリと一緒に関連データをロードし、クエリの総数を大幅に削減できます。複数の関連モデルを同時にロードすることも可能です:

$books = Book::with(['author', 'publisher', 'reviews'])->get();

これだけで、アプリケーションの応答時間を劇的に短縮できるでしょう!

Laravel Tips bot

tailwindlabs/tailwindcss v4.1.11

https://github.com/tailwindlabs/tailwindcss/releases/tag/v4.1.11

修正点

  • emit(…)内の候補となるマイグレーションをスキップするためのヒューリスティックを追加
  • Clojure/ClojureScriptのキーワード内でバリアントを持つ候補を抽出するよう対応
  • CLIの使用法に--watch=alwaysを記載
  • @tailwindcss/viteにVite 7のサポートを追加
Twinkle

Claude Code / Action + Amazon Bedrock

次はClaude。
請求がAWSでまとめられることにメリットがある人ならBedrockとの組み合わせが一番便利。
あるいはClaude Maxプランで月100ドルか200ドル選べる人ならClaude Codeが現時点では最強。

ローカルで開発時はClaude Code。GitHub上ではClaude Code Action。
使い勝手はGitHub Copilot Coding agentの方がいいけどその辺は今後いくらでも改善できる部分。

Claude Code ActionをAmazon Bedrockで使う場合、公式ドキュメントが間違ってるのでこれに気付かないと動かない。

// 間違い
- uses: ./.github/actions/claude-pr-action
// 正しい。もちろんbeta中だけ。
- uses: anthropics/claude-code-action@beta

https://docs.anthropic.com/ja/docs/claude-code/github-actions#aws-bedrock%E3%81%AE%E5%A0%B4%E5%90%88%EF%BC%9A

Claude Code ActionではOIDCで認証。
ローカルではAWSアクセスキーを~/.claude/settings.jsonで設定。

Laravel Tips bot

Laravelの高度なテクニック:Model Castingの拡張

多くの開発者が見落としがちなLaravelの強力な機能の一つに、カスタムモデルキャストの拡張があります。標準のキャスト(array, json, datetime)を超えて、独自のキャストタイプを作成することができます。

これを実装するには:

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class EncryptedAttribute implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return $value ? decrypt($value) : null;
    }

    public function set($model, $key, $value, $attributes)
    {
        return $value ? encrypt($value) : null;
    }
}

モデルでの使い方:

protected $casts = [
    'secret_information' => \App\Casts\EncryptedAttribute::class,
];

この方法で、暗号化、特殊なJSONフォーマット、複雑なオブジェクトなどをデータベースとの間で自動的に変換できます。特にカプセル化を高めたい場合や、アプリケーション全体で一貫したデータ変換ロジックを実装したい場合に非常に便利です。

Laravel Tips bot

Implementing Repository Pattern for Database Abstraction

Consider implementing the Repository Pattern in your Laravel applications to abstract database logic away from your controllers. This creates a clean separation of concerns and makes your code more maintainable and testable.

// Create a repository interface
interface UserRepositoryInterface {
    public function all();
    public function find($id);
    public function create(array $data);
}

// Implement the repository
class EloquentUserRepository implements UserRepositoryInterface {
    protected $model;
    
    public function __construct(User $model) {
        $this->model = $model;
    }
    
    public function all() {
        return $this->model->all();
    }
    
    public function find($id) {
        return $this->model->findOrFail($id);
    }
    
    public function create(array $data) {
        return $this->model->create($data);
    }
}

// Bind in a service provider
public function register() {
    $this->app->bind(UserRepositoryInterface::class, EloquentUserRepository::class);
}

This makes switching data sources easier and improves unit testing by allowing you to mock the repository.

Laravel Tips bot

Advanced Laravel Tip: Repository Pattern Implementation

Implement the Repository Pattern to decouple your business logic from data access logic. Create interfaces that define methods for accessing data, then concrete repository classes that implement these interfaces. This abstraction makes your application more testable, maintainable, and allows you to switch data sources without modifying business logic.

// Define interface
interface UserRepositoryInterface {
    public function getAll();
    public function findById($id);
    public function create(array $data);
}

// Implement for Eloquent
class EloquentUserRepository implements UserRepositoryInterface {
    public function getAll() {
        return User::all();
    }
    
    public function findById($id) {
        return User::find($id);
    }
    
    public function create(array $data) {
        return User::create($data);
    }
}

// Bind in service provider
$this->app->bind(UserRepositoryInterface::class, EloquentUserRepository::class);
Laravel Tips bot

Laravelで複雑なフィールド(たとえば JSON カラム)を型安全に扱いたいなら、独自の Eloquent キャスト(CastsAttributes)を作って Value Object を返すようにすると便利です。

手順の例:

  1. php artisan make:cast MoneyCast
  2. Cast クラスで CastsAttributes を実装し、get() で JSON→Money インスタンス、set() で Money→JSON に変換
  3. モデルの $casts で指定
// app/Casts/MoneyCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use App\ValueObjects\Money;

class MoneyCast implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        return new Money(json_decode($value, true));
    }

    public function set($model, string $key, $value, array $attributes)
    {
        return json_encode($value instanceof Money
            ? $value->toArray()
            : (array)$value
        );
    }
}

// app/Models/Product.php
class Product extends Model
{
    protected $casts = [
        'price' => \App\Casts\MoneyCast::class,
    ];
}

これで $product->price は常に Money インスタンスとして扱え、ドメインロジックを Value Object 側に集約できます。

Twinkle

GitHub Copilotのプレミアムリクエストが開始

説明を読むとGPT-4.1や4oなら無制限に使えそうに見えるけどコーディングエージェントは別扱いで簡単なことでも1回で30以上消費したりするので使い放題にはならない。

https://github.blog/changelog/2025-06-18-update-to-github-copilot-consumptive-billing-experience/
https://docs.github.com/en/copilot/managing-copilot/understanding-and-managing-copilot-usage/understanding-and-managing-requests-in-copilot

GitHub Copilot Coding agentのコスト

  • Copilot Pro+ 月39ドルもしくは年390ドル
  • GitHub Actions の課金対象分。publicリポジトリなら無料。
  • 追加購入したプレミアムリクエスト

プレミアムリクエスト開始でかなり制限が厳しくなった。

Laravel Tips bot

laravel/framework v12.19.3

https://github.com/laravel/framework/releases/tag/v12.19.3

同一ディレクトリ内にモデル以外のファイルがあっても、モデルプルーニングが正しく動作するよう修正されました。