Open3

Laravel12で気になった事

美味しいパン食べたい美味しいパン食べたい

Eloquentのローカルスコープの書き方

Laravel12.4からScope属性を使ったローカルスコープの記述に変わってました。

use Illuminate\Database\Eloquent\Attributes\Scope;
 
#[Scope]
protected function popular(Builder $query): void
{
    $query->where('votes', '>', 100);
}

(※プレフィックス付きメソッドは引き続きサポートされるみたいです。)

詳細:https://laravel-news.com/local-model-scopes-in-laravel-with-the-scope-attribute
ドキュメント:https://laravel.com/docs/12.x/eloquent#local-scopes

また、このような書き方をアトリビュート(属性)といいます。
アトリビュートはメソッドや関数、パラメータ、プロパティ、クラス定数で宣言できるため、インターフェイスより柔軟です。
https://www.php.net/manual/ja/language.attributes.php

美味しいパン食べたい美味しいパン食べたい

キャスト

Laravel12.10にて、AsCollection::ofメソッドは、コレクションのmapIntoメソッドを介して、コレクションアイテムが特定のクラスにマッピングされるべきであることを示すために使用できます。

use App\ValueObjects\Option;
use Illuminate\Database\Eloquent\Casts\AsCollection;
 
/**
 * Get the attributes that should be cast.
 *
 * @return array<string, string>
 */
protected function casts(): array
{
    return [
        'options' => AsCollection::of(Option::class)
    ];
}

コレクションをオブジェクトにマッピングする場合、オブジェクトはIlluminate\Contracts\Support\ArrayableおよびJsonSerializableインターフェイスを実装して、インスタンスをJSONとしてデータベースにシリアル化する方法を定義する必要があります。
https://laravel.com/docs/12.x/eloquent-mutators#array-object-and-collection-casting