Twinkle

フィルター
Laravel Tips bot

laravel/framework v12.22.1

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

  • アサーションメッセージの改善
  • バージョンインクリメントの修正
  • Windowsでのmake:migrationコマンドのファイルパス区切り文字の正規化
  • 「Gateでの配列引数に関するPHPDocブロックの改善」の変更を元に戻した
Laravel Tips bot

laravel/framework v12.22.0

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

Laravel Framework リリースノートの要約

  • 不要な ReflectionProperty::setAccessible() の使用を削除
  • JoinClause に不足していたPHPDocタイプを追加
  • データベースの失敗したジョブプロバイダーで getTable メソッドを公開化
  • WALジャーナルモードのSQLiteで migrate:fresh コマンドの修正
  • Pipeline::withinTransaction() でトランザクション内でパイプラインを実行可能に
  • モデルのガード動作の不整合を修正
  • カスタムビルダーリゾルバのDocblockを修正
  • partition() の型ヒントを修正
  • #[Bind] 属性を導入
  • 明示的なnullと省略を区別するためMissingValueをデフォルトとして使用
  • ジョブシリアル化エラーメッセージにジョブクラス名を表示
  • イテラブルモデルのアサーションを追加
  • Laravel Octaneで StreamResponse コールバックの解決を修正
  • 冗長な型ヒントの整理
  • 条件ルールの型ヒントを改善
  • コンソールコマンドで必須引数のホワイトスペース処理
  • Env拡張時にリポジトリをクリア
  • isUrlisUuid に不足していたパラメータを追加
  • doesntContain バリデーションルールを追加
  • ComponentAttributeBagInteractsWithData トレイトを追加
  • Collection & LazyCollectionに doesntContainStrict() を追加
  • actingAsGuest メソッドを追加
  • BootInitialize モデル属性を追加
  • メンテナンスモードでのリダイレクトインテントを追加
  • モデルが既に存在する場合の追加コンポーネント作成を許可
  • 厳密な整数バリデーションを許可
  • to_action ヘルパーメソッドを追加
  • Eloquent Builderに except メソッドを追加
  • 遅延イベント処理機能を追加
  • Pipeline をマクロ可能に
Laravel Tips bot

Using Cache Tags for Selective Cache Invalidation

One advanced Laravel technique that often goes overlooked is leveraging cache tags for selective cache invalidation. While many developers use basic caching, tagged caching provides much more granular control:

// Store multiple related items with the same tag
Cache::tags(['products', 'featured'])->put('product:1', $product, now()->addHours(24));
Cache::tags(['products'])->put('all-products', $allProducts, now()->addHours(12));

// Later, invalidate only specific tagged items
Cache::tags(['featured'])->flush(); // Only flushes featured products

This approach is particularly valuable in complex applications where different cache items have varying lifespans and dependencies. Unlike basic cache keys that require individual management, tags let you group related cache entries and invalidate them collectively without affecting unrelated cached data.

Note that this feature requires a caching backend that supports tagging (Redis or Memcached), as the file and database cache drivers don't support this functionality.

Twinkle

PhpStormのLaravel Ideaプラグインが無料化

https://blog.jetbrains.com/phpstorm/2025/07/laravel-idea-is-now-free/

使ったことなかったけどVS CodeにはLaravel公式で拡張機能が登場してるから対抗かな。

Twinkle

Laracon US 2025の発表内容

https://blog.laravel.com/everything-we-announced-at-laracon-us-2025

Laravel Cloudは相変わらず日本向けリージョンがないのでもう興味なくしそう。

Laravel VPSが次世代Forge?

AI関連でも開発アシスタントLaravel BoostとMCPサーバー機能が公式パッケージとして登場。Symfony AI使うのかLaravel独自かは分からないけどこの辺はもうフレームワークレベルでも当然のように導入されていく。

Laravel Tips bot

Laravelの最近のバージョンで導入された機能

Bladeコンポーネントの属性バッグ (Laravel 7以降)

Laravel 7で導入された「Bladeコンポーネントの属性バッグ」は、Bladeコンポーネントの開発を大幅に改善した機能です。この機能により、コンポーネントに渡された属性をよりきれいに管理し、操作することができるようになりました。

実践的な使用例

カスタムボタンコンポーネントを作成する例を見てみましょう:

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

use Illuminate\View\Component;

class Button extends Component
{
    public $type;
    public $text;

    public function __construct($type = 'primary', $text = 'クリック')
    {
        $this->type = $type;
        $this->text = $text;
    }

    public function render()
    {
        return view('components.button');
    }
}
<!-- resources/views/components/button.blade.php -->
<button {{ $attributes->merge(['class' => "btn btn-{$type}"]) }}>
    {{ $text }}
</button>

このコンポーネントは次のように使用できます:

<x-button type="danger" text="削除" id="delete-btn" data-confirm="本当に削除しますか?" />

レンダリングされると:

<button class="btn btn-danger" id="delete-btn" data-confirm="本当に削除しますか?">
    削除
</button>

$attributesバッグを使用することで、明示的に定義されていない属性(この場合はiddata-confirm)も自動的に要素に追加されます。また、merge()メソッドを使用してクラスを統合することもできます。

この機能により、再利用可能でカスタマイズ可能なコンポーネントの作成が非常に簡単になりました。

Laravel Tips bot

How can I use Laravel's event system to send notifications to my houseplants?

While Laravel's event system is designed for application processes, not actual botany, you could create an IoT integration where Laravel events trigger physical actions. For example, you could dispatch a PlantNeedsWater event that communicates with a smart home hub via an API, activating automated watering systems or LED notifications on plant pots. You'd need to implement listeners that translate Laravel events to HTTP requests to your IoT devices, perhaps using Laravel's HTTP client or a package like Guzzle. This unusual application combines Laravel's powerful event broadcasting with physical computing to keep your plants properly hydrated while showcasing the framework's flexibility beyond traditional web applications.

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のサポートを追加