Readouble

Laravel 8.x アップグレードガイド

重要度の高い変更High Impact Changes

重要度が中程度の変更Medium Impact Changes

7.xから8.0へのアップグレードUpgrading To 8.0 From 7.x

アップグレード見積もり時間:15分Estimated Upgrade Time: 15 Minutes

Note: note 私達は、互換性を失う可能性がある変更を全部ドキュメントにしようとしています。しかし、変更点のいくつかは、フレームワークの明確ではない部分で行われているため、一部の変更が実際にアプリケーションに影響を与えてしまう可能性があります。{note} We attempt to document every possible breaking change. Since some of these breaking changes are in obscure parts of the framework only a portion of these changes may actually affect your application.

動作条件:PHP7.3.0PHP 7.3.0 Required

影響の可能性: 中程度Likelihood Of Impact: Medium

新しく必要なPHPの最低バージョンが7.3.0になりました。The new minimum PHP version is now 7.3.0.

依存パッケージのアップデートUpdating Dependencies

composer.jsonファイル中に指定されている以下のパッケージ依存を更新してください。Update the following dependencies in your composer.json file:

  • guzzlehttp/guzzle^7.0.1guzzlehttp/guzzle to ^7.0.1
  • facade/ignition^2.3.6facade/ignition to ^2.3.6
  • laravel/framework^8.0laravel/framework to ^8.0
  • laravel/ui^3.0laravel/ui to ^3.0
  • nunomaduro/collision^5.0nunomaduro/collision to ^5.0
  • phpunit/phpunit^9.0phpunit/phpunit to ^9.0

以下のファーストパーティパッケージは、Laravel8をサポートするために、新しくメジャーバージョンになりました。該当するパッケージを使用している場合、アップグレードを行う前に、各アップグレードガイドを読んでください。The following first-party packages have new major releases to support Laravel 8. If applicable, you should read their individual upgrade guides before upgrading:

  • Horizon v5.0Horizon v5.0[https://github.com/laravel/horizon/blob/master/UPGRADE.md]
  • Passport v10.0Passport v10.0[https://github.com/laravel/passport/blob/master/UPGRADE.md]
  • Socialite v5.0Socialite v5.0[https://github.com/laravel/socialite/blob/master/UPGRADE.md]
  • Telescope v4.0Telescope v4.0[https://github.com/laravel/telescope/blob/master/UPGRADE.md]

さらに、Laravelインストーラをcomposer create-projectとLaravel Jetstreamをサポートするためにアップデートしました。4.0より古いインストーラは2020年の10月以降動作停止します。グローバルインストーラを^4.0へすぐにアップデートしてください。In addition, the Laravel installer has been updated to support composer create-project and Laravel Jetstream. Any installer older than 4.0 will cease to work after October 2020. You should upgrade your global installer to ^4.0 as soon as possible.

最後にアプリケーションで使用してる、その他のサードパーティパッケージを調べ、Laravel8をサポートしているバージョンを確実に使用しているかを検証してください。Finally, examine any other third-party packages consumed by your application and verify you are using the proper version for Laravel 8 support.

コレクションCollections

issetメソッドThe isset Method

影響の可能性: 低いLikelihood Of Impact: Low

典型的なPHPの動作と整合性をとるため、Illuminate\Support\CollectionoffsetExistsメソッドはarray_key_existsの代わりにissetを使用するように変更しました。これにより値がnullのコレクションアイテムを扱う際の挙動に変化の生じる可能性があります。To be consistent with typical PHP behavior, the offsetExists method of Illuminate\Support\Collection has been updated to use isset instead of array_key_exists. This may present a change in behavior when dealing with collection items that have a value of null:

$collection = collect([null]);

// Laravel7.x - true
isset($collection[0]);

// Laravel8.x - false
isset($collection[0]);

DatabaseDatabase

シーダとファクトリの名前空間Seeder & Factory Namespaces

影響の可能性: 高いLikelihood Of Impact: High

シーダとファクトリは名前空間になりました。これらの変更に対応するには、Database\Seeders名前空間をシードクラスに追加します。さらに、以前のdatabase/seedsディレクトリの名前をdatabase/seedersに変更する必要があります:Seeders and factories are now namespaced. To accommodate for these changes, add the Database\Seeders namespace to your seeder classes. In addition, the previous database/seeds directory should be renamed to database/seeders:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * アプリケーションのデータベースの初期値設定
     *
     * @return void
     */
    public function run()
    {
        ...
    }
}

laravel/legacy-factoriesパッケージを使用する場合は、ファクトリクラスを変更する必要はありません。ただし、ファクトリをアップグレードする場合は、それらのクラスにDatabase\Factories名前空間を追加する必要があります。If you are choosing to use the laravel/legacy-factories package, no changes to your factory classes are required. However, if you are upgrading your factories, you should add the Database\Factories namespace to those classes.

次に、composer.jsonファイルで、autoloadセクションからclassmapブロックを削除し、新しい名前空間クラス・ディレクトリマッピングを追加します。Next, in your composer.json file, remove classmap block from the autoload section and add the new namespaced class directory mappings:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},

EloquentEloquent

モデルファクトリModel Factories

影響の可能性: 高いLikelihood Of Impact: High

Laravelのモデルファクトリ機能は、クラスをサポートするよう完全に書き直されており、Laravel7.xスタイルのファクトリとは互換性がありません。ただし、アップグレードプロセスを簡単にするため、新しいlaravel/legacy-factoriesパッケージが作成され、Laravel 8.xで既存のファクトリを続けて使用できます。このパッケージはComposerでインストールできます。Laravel's model factories[/docs/{{version}}/database-testing#defining-model-factories] feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories. However, to ease the upgrade process, a new laravel/legacy-factories package has been created to continue using your existing factories with Laravel 8.x. You may install this package via Composer:

composer require laravel/legacy-factories

CastableインターフェイスThe Castable Interface

影響の可能性: 低いLikelihood Of Impact: Low

CastableインターフェイスのcastUsingメソッドは、引数の配列を引数に取るように更新されました。このインターフェイスを実装している場合は、それに応じて実装を更新する必要があります。The castUsing method of the Castable interface has been updated to accept an array of arguments. If you are implementing this interface you should update your implementation accordingly:

public static function castUsing(array $arguments);

Increment/DecrementイベントIncrement / Decrement Events

影響の可能性: 低いLikelihood Of Impact: Low

Eloquentモデルインスタンスでincrementまたは decrementメソッドの実行時に"update"と"save"で適切な関連モデルイベントが発行されるようになりました。Proper "update" and "save" related model events will now be dispatched when executing the increment or decrement methods on Eloquent model instances.

イベントEvents

EventServiceProviderクラスThe EventServiceProvider Class

影響の可能性: 低いLikelihood Of Impact: Low

App\Providers\EventServiceProviderクラスにregister関数が含まれている場合は、このメソッドの先頭で確実にparent::registerを呼び出す必要があります。そうしないと、アプリケーションのイベントは登録されません。If your App\Providers\EventServiceProvider class contains a register function, you should ensure that you call parent::register at the beginning of this method. Otherwise, your application's events will not be registered.

Dispatcher契約The Dispatcher Contract

影響の可能性: 低いLikelihood Of Impact: Low

Illuminate\Contracts\Events\Dispatcher契約のlistenメソッドを変更し、$listenerプロパティをオプションにしました。この変更は、リフレクションを介して処理されるイベントタイプの自動検出をサポートするために行いました。このインターフェイスを自分で実装している場合は、対応する実装を更新する必要があります。The listen method of the Illuminate\Contracts\Events\Dispatcher contract has been updated to make the $listener property optional. This change was made to support automatic detection of handled event types via reflection. If you are manually implementing this interface, you should update your implementation accordingly:

public function listen($events, $listener = null);

フレームワークFramework

メンテナンスモードアップデートMaintenance Mode Updates

影響の可能性: 状況によるLikelihood Of Impact: Optional

Laravel8.xではメンテナンスモード機能が改善されています。メンテナンスモードテンプレートの事前レンダリングをサポートし、メンテナンスモード中にエンドユーザーがエラーに遭遇する可能性が少なくなりました。ただし、これをサポートするには、以降をpublic/index.phpファイルに追加しなくてはなりません。これらの行は既存のLARAVEL_START定数の定義直下に配置してください。The maintenance mode[/docs/{{version}}/configuration#maintenance-mode] feature of Laravel has been improved in Laravel 8.x. Pre-rendering the maintenance mode template is now supported and eliminates the chances of end users encountering errors during maintenance mode. However, to support this, the following lines must be added to your public/index.php file. These lines should be placed directly under the existing LARAVEL_START constant definition:

define('LARAVEL_START', microtime(true));

if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
    require __DIR__.'/../storage/framework/maintenance.php';
}

php artisan down --messageオプションThe php artisan down --message Option

影響の可能性: 中程度Likelihood Of Impact: Medium

php artisan downコマンドの --messageオプションを削除しました。別の方法として、選択したメッセージでメンテナンスモードビューの事前レンダリングの使用を検討してください。The --message option of the php artisan down command has been removed. As an alternative, consider pre-rendering your maintenance mode views[/docs/{{version}}/configuration#maintenance-mode] with the message of your choice.

The php artisan serve --no-reload OptionThe php artisan serve --no-reload Option

影響の可能性: 低いLikelihood Of Impact: Low

php artisan serveコマンドに --no-reloadオプションを追加しました。これにより、環境ファイルの変更が検出されたときにサーバをリロードしないように組み込みサーバに指示できます。このオプションは主にCI環境でLaravelDuskテストを実行するときに役立ちます。A --no-reload option has been added to the php artisan serve command. This will instruct the built-in server to not reload the server when environment file changes are detected. This option is primarily helpful when running Laravel Dusk tests in a CI environment.

$appプロパティマネージャーManager $app Property

影響の可能性: 低いLikelihood Of Impact: Low

以前非推奨になった Illuminate\Support\Managerクラスの$appプロパティを削除しました。このプロパティに依存している場合は、代わりに$containerプロパティを使用してください。The previously deprecated $app property of the Illuminate\Support\Manager class has been removed. If you were relying on this property, you should use the $container property instead.

elixirヘルパThe elixir Helper

影響の可能性: 低いLikelihood Of Impact: Low

以前、非推奨にした、elixirヘルパを削除しました。このメソッドをまだ使用しているアプリケーションは、Laravel Mixへアップグレードすることをおすすめします。The previously deprecated elixir helper has been removed. Applications still using this method are encouraged to upgrade to Laravel Mix[https://github.com/JeffreyWay/laravel-mix].

メールMail

sendNowメソッドThe sendNow Method

影響の可能性: 低いLikelihood Of Impact: Low

以前非推奨にした、sendNowメソッドを削除しました。代わりに、sendメソッドを使用してください。The previously deprecated sendNow method has been removed. Instead, please use the send method.

ペジネーションPagination

ペジネーションデフォルトPagination Defaults

影響の可能性: 高いLikelihood Of Impact: High

ペジネータは、デフォルトのスタイルにTailwind CSSフレームワークを使用するようにしました。Bootstrapを使い続けるには、以降のメソッド呼び出しをアプリケーションのAppServiceProviderbootメソッドに追加してください。The paginator now uses the Tailwind CSS framework[https://tailwindcss.com] for its default styling. In order to keep using Bootstrap, you should add the following method call to the boot method of your application's AppServiceProvider:

use Illuminate\Pagination\Paginator;

Paginator::useBootstrap();

キューQueue

retryAfterメソッドThe retryAfter Method

影響の可能性: 高いLikelihood Of Impact: High

Laravelの他の機能との整合性を保つため、キュー投入したジョブ、メーラ、通知、リスナのretryAfterメソッドとretryAfterプロパティは、backoffに改名しました。アプリケーションの関連クラスで、このメソッドとプロパティの名前を変更してください。For consistency with other features of Laravel, the retryAfter method and retryAfter property of queued jobs, mailers, notifications, and listeners have been renamed to backoff. You should update the name of this method / property in the relevant classes in your application.

timeoutAtプロパティThe timeoutAt Property

影響の可能性: 高いLikelihood Of Impact: High

キュー投入したジョブ、通知、リスナのtimeoutAtプロパティの名前をretryUntilへ改名しました。アプリケーションの関連クラスで、このプロパティの名前を変更してください。The timeoutAt property of queued jobs, notifications, and listeners has been renamed to retryUntil. You should update the name of this property in the relevant classes in your application.

allOnQueue()allOnConnection()メソッドThe allOnQueue() / allOnConnection() Methods

影響の可能性: 高いLikelihood Of Impact: High

他のディスパッチメソッドとの一貫性を保つため、ジョブチェーンで使用されていたallOnQueue()メソッドとallOnConnection()メソッドを削除しました。代わりに、onQueue()メソッドとonConnection()メソッドを使用してください。これらのメソッドは、dispatchメソッドを呼び出す前に呼び出す必要があります。For consistency with other dispatching methods, the allOnQueue() and allOnConnection() methods used with job chaining have been removed. You may use the onQueue() and onConnection() methods instead. These methods should be called before calling the dispatch method:

ProcessPodcast::withChain([
    new OptimizePodcast,
    new ReleasePodcast
])->onConnection('redis')->onQueue('podcasts')->dispatch();

この変更は、 withChainメソッドを使用するコードにのみ影響することに注意してください。グローバルなdispatch()ヘルパを使用している場合でも、allOnQueue()allOnConnection()は引き続き使用できます。Note that this change only affects code using the withChain method. The allOnQueue() and allOnConnection() are still available when using the global dispatch() helper.

失敗したジョブテーブルのバッチサポートFailed Jobs Table Batch Support

影響の可能性: 状況によるLikelihood Of Impact: Optional

Laravel8.xのジョブのバッチ処理機能を使用する場合は、failed_jobsデータベーステーブルを更新する必要があります。最初に、新しいuuid列をテーブルに追加してください。If you plan to use the job batching[/docs/{{version}}/queues#job-batching] features of Laravel 8.x, your failed_jobs database table will need to be updated. First, a new uuid column should be added to your table:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('failed_jobs', function (Blueprint $table) {
    $table->string('uuid')->after('id')->nullable()->unique();
});

次に、queue設定ファイル内のfailed.driver設定オプションをdatabase-uuidsに更新してください。Next, the failed.driver configuration option within your queue configuration file should be updated to database-uuids.

さらに、既存の失敗したジョブに対し、UUIDを生成できます。In addition, you may wish to generate UUIDs for your existing failed jobs:

DB::table('failed_jobs')->whereNull('uuid')->cursor()->each(function ($job) {
    DB::table('failed_jobs')
        ->where('id', $job->id)
        ->update(['uuid' => (string) Illuminate\Support\Str::uuid()]);
});

ルーティングRouting

コントローラ名前空間の自動プレフィクスAutomatic Controller Namespace Prefixing

影響の可能性: 状況によるLikelihood Of Impact: Optional

以前のLaravelリリースでは、RouteServiceProviderクラスにApp\Http\Controllersの値を持つ$namespaceプロパティが存在していました。このプロパティの値は、コントローラルート定義とコントローラルートURL生成時に、actionヘルパを呼び出す際などに自動的にプレフィックスを付けるために使われていました。In previous releases of Laravel, the RouteServiceProvider class contained a $namespace property with a value of App\Http\Controllers. The value of this property was used to automatically prefix controller route declarations and controller route URL generation such as when calling the action helper.

Laravel8では、このプロパティをデフォルトでnullに設定しています。これにより、コントローラのルート宣言でPHP標準callable構文を使用できるようになり、多くのIDEでコントローラクラスへのジャンプがより良くサポートされます。In Laravel 8, this property is set to null by default. This allows your controller route declarations to use the standard PHP callable syntax, which provides better support for jumping to the controller class in many IDEs:

use App\Http\Controllers\UserController;

// PHPのcallable記法
Route::get('/users', [UserController::class, 'index']);

// 文字列記法の使用
Route::get('/users', 'App\Http\Controllers\UserController@index');

ほとんどの場合、RouteServiceProviderには以前の値の$namespaceプロパティが含まれているため、アップグレードしているアプリケーションには影響がありません。しかし、新しいLaravelプロジェクトを作成し、アプリケーションをアップグレードした場合は、この重大な変更に遭遇するでしょう。In most cases, this won't impact applications that are being upgraded because your RouteServiceProvider will still contain the $namespace property with its previous value. However, if you upgrade your application by creating a brand new Laravel project, you may encounter this as a breaking change.

もとの自動プレフィクス付きコントローラルーティングを使い続けたい場合は、RouteServiceProvider内の $namespaceプロパティの値を設定し、bootメソッド内のルート登録を$namespaceプロパティを使用するように変更します。If you would like to continue using the original auto-prefixed controller routing, you can simply set the value of the $namespace property within your RouteServiceProvider and update the route registrations within the boot method to use the $namespace property:

class RouteServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションの"home"ルートのパス
     *
     * ログイン後にユーザーをリダイレクトするため、Laravel認証が使用する
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * 指定されている場合、コントローラルートへ自動的に適用される名前空間
     *
     * さらに、URLジェネレータのルート名前空間としてセット
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * ルートモデル結合、パターンフィルタなどを定義
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
        });
    }

    /**
     * アプリケーションのレート制限の設定
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }
}

スケジュールScheduling

cron-expressionライブラリThe cron-expression Library

影響の可能性: 低いLikelihood Of Impact: Low

Laravelの依存パッケージであるdragonmantank/cron-expressionが、2.xから3.xへ更新されました。これにより、cron-expressionライブラリと直接操作していない限り、アプリケーションが壊れるような変化は起こらないはずです。このライブラリを直接やりとりする場合は、変更ログを確認してください。Laravel's dependency on dragonmantank/cron-expression has been updated from 2.x to 3.x. This should not cause any breaking change in your application unless you are interacting with the cron-expression library directly. If you are interacting with this library directly, please review its change log[https://github.com/dragonmantank/cron-expression/blob/master/CHANGELOG.md].

セッションSession

Session契約The Session Contract

影響の可能性: 低いLikelihood Of Impact: Low

IlluminateContracts\Session\SessionSession 契約に新しいpullメソッドを追加しました。自分で実装している場合は、これに合わせて実装を更新してください。The Illuminate\Contracts\Session\Session contract has received a new pull method. If you are implementing this contract manually, you should update your implementation accordingly:

/**
 * 指定キーの値を取得し、次に削除
 *
 * @param  string  $key
 * @param  mixed  $default
 * @return mixed
 */
public function pull($key, $default = null);

テストTesting

decodeResponseJsonメソッドThe decodeResponseJson Method

影響の可能性: 低いLikelihood Of Impact: Low

Illuminate\Testing\TestResponseクラスに属するdecodeResponseJsonメソッドは、引数を取らなくなりました。代わりにjsonメソッドの使用を検討してください。The decodeResponseJson method that belongs to the Illuminate\Testing\TestResponse class no longer accepts any arguments. Please consider using the json method instead.

assertExactJsonメソッドThe assertExactJson Method

影響の可能性: 中程度Likelihood Of Impact: Medium

assertExactJsonメソッドは、比較する配列の数値キーが一致し、同じ順序であることを必要とするようになりました。配列の数値キーの順序を同じにすることなく、JSONを配列と比較したい場合は代わりにassertSimilarJsonメソッドが使用できます。The assertExactJson method now requires numeric keys of compared arrays to match and be in the same order. If you would like to compare JSON against an array without requiring numerically keyed arrays to have the same order, you may use the assertSimilarJson method instead.

バリデーションValidation

データベースルールの接続Database Rule Connections

影響の可能性: 低いLikelihood Of Impact: Low

unique および exists ルールはクエリを実行する際に、Eloquentモデルで指定した(モデルのgetConnectionNameメソッドによりアクセスした)接続名を尊重するようになりました。The unique and exists rules will now respect the specified connection name (accessed via the model's getConnectionName method) of Eloquent models when performing queries.

その他Miscellaneous

laravel/laravelGitHubリポジトリで、変更を確認することを推奨します。これらの変更は必須でありませんが、皆さんのアプリケーションではファイルの同期を保つほうが良いでしょう。変更のいくつかは、このアップグレードガイドで取り扱っていますが、設定ファイルやコメントなどの変更は取り扱っていません。変更は簡単にGitHubの比較ツールで閲覧でき、みなさんにとって重要な変更を選択できます。We also encourage you to view the changes in the laravel/laravel GitHub repository[https://github.com/laravel/laravel]. While many of these changes are not required, you may wish to keep these files in sync with your application. Some of these changes will be covered in this upgrade guide, but others, such as changes to configuration files or comments, will not be. You can easily view the changes with the GitHub comparison tool[https://github.com/laravel/laravel/compare/7.x...8.x] and choose which updates are important to you.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作