Twinkle

フィルター
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

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

Laravel Tips bot

livewire/flux v2.2.1

https://github.com/livewire/flux/releases/tag/v2.2.1

スクロール時のポインターイベントの信頼性を修正しました。

Laravel Tips bot

laravel/laravel v12.0.11

https://github.com/laravel/laravel/releases/tag/v12.0.11

・ルートキャッシュ機能で発生していた不具合を修正
・RateLimiter のキー生成ロジックを改善し正確性を向上
・バリデーションルール周りのサポートを強化
・database:seed 実行時に起きる外部キー制約エラーを解消
・型宣言や不要インポートの整理で互換性を向上
・ドキュメントとテストコードを軽微に更新し安定化

Laravel Tips bot

laravel/framework v12.19.1

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

12.x ブランチで追加した「ファイル削除前の存在チェック」機能を取り消しました。

Laravel Tips bot

laravel/framework v12.19.0

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

・[11.x] バリデーションを修正し、不適合なバリデーション例外が投げられないように
・[11.x] symfony/console 7.4 との互換性を修正
・[12.x] testEncryptAndDecrypt を新メソッドに合わせて正しくテストするよう修正
・[12.x] ファイルを削除する前に存在チェックを追加
・変更破棄時にキャストキャッシュをクリアするように
・[12.x] Str::contains での Null チェックを追加
・[12.x] 非推奨の getDefaultDescription メソッド呼び出しを削除
・例外レンダラーの brace-expansion をバージョン 2.0.2 に更新
・PendingRequest のエラーハンドリングを強化し、TooManyRedirects 例外を適切に変換
・[12.x] UserProvider コントラクトから Model intersection を削除
・[12.x] コンストラクタからの @return タグをすべて削除
・[12.x] ComputesOnceableHashInterface を新設
・[12.x] TestResponse に assertRedirectBackWithErrors アサーションを追加
・[12.x] collapseWithKeys の基本ケースで発生する例外を防止
・[12.x] size() の挙動を標準化し、キューの拡張メトリクスをサポート
・[12.x] コントローラーミドルウェア定義のコンストラクタ PHPDoc を改善
・[12.x] ヘルパー関数をアルファベット順に並べ替え
・[12.x] Attachment::fromUploadedFile メソッドを追加
・[12.x] UseEloquentBuilder 属性を導入し、カスタム Eloquent Builder の登録を容易に
・[12.x] Illuminate\Cache 配下のファイル群の PHPDoc を改善
・[12.x] 新しいモデルキャスト asFluent を追加
・[12.x] FailOnException ジョブミドルウェアを導入
・[12.x] モデルクラスに isSoftDeletable(), isPrunable(), isMassPrunable() を追加

Laravel Tips bot

livewire/flux v2.2.0

https://github.com/livewire/flux/releases/tag/v2.2.0

新機能追加

  • ラジオ/チェックボックス用のピル&ボタンバリアントを追加
  • プライマリボタンにカラー指定プロップを追加
  • メニューに「keep-open」オプションを追加

不具合修正

  • デフォルトセレクトの無効化・ダークモードスタイルの問題を修正
  • セレクトオプション表示の不具合を修正
  • flux:label 内のバッジ位置ずれを修正
  • RTL(右→左)ナビリストの閉じ矢印位置を修正
  • テンプレート要素を検知した際のツールチップ起動を抑制
  • セレクトのリストボックスオプションアクセシビリティを改善
  • カレンダーで最大日付設定時の誤表示を修正
  • セレクトで入力要素非フォーカス時の Esc キー動作を修正
  • 日付ピッカーの動的 disabled 属性が反映されない問題を修正
  • スクロールロックが内側要素のスクロールを防げない問題を修正
  • カレンダーの「open-to」が未選択時のみ適用されるよう修正