Readouble

Laravel 5.4 アップグレードガイド

5.3から5.4.0へのアップグレードUpgrading To 5.4.0 From 5.3

アップグレード見積もり時間 1〜2時間Estimated Upgrade Time: 1-2 Hours

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.

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

composer.jsonファイル中の、laravel/framework依存パッケージ指定のバージョンを5.4.*へ更新してください。さらに、依存パッケージのphpunit/phpunit~5.7へ更新してください。Update your laravel/framework dependency to 5.4.* in your composer.json file. In addition, you should update your phpunit/phpunit dependency to ~5.7.

コンパイル済みサービスファイルの削除Removing Compiled Services File

存在している場合は、bootstrap/cache/compiled.phpファイルを削除してください。フレームワークで使用しなくなりました。If it exists, you may delete the bootstrap/cache/compiled.php file. It is no longer used by the framework.

キャッシュのクリアFlushing The Cache

全パッケージを更新したら、Illuminate\View\Factory::getFirstLoop()の削除に関連するBladeのエラーを防ぐために、php artisan view:clearを実行してください。さらに、ルートキャッシュをクリアするために、php artisan route:clearも行う必要があります。After upgrading all packages, you should run php artisan view:clear to avoid Blade errors related to the removal of Illuminate\View\Factory::getFirstLoop(). In addition, you may need to run php artisan route:clear to flush the route cache.

Laravel CashierLaravel Cashier

Laravel CashierはLaravel5.4へ既に対応しています。Laravel Cashier is already compatible with Laravel 5.4.

Laravel PassportLaravel Passport

Laravel Passport 2.0.0は既にLaravel5.4とAxios JavaScriptライブラリへ対応しています。Laravel5.3で既に構築済みのPassprt Vueコンポーネントを使用中の場合は、Axiosライブラリをaxiosとしてアプリケーション全体で、確実に使用できるようにしてください。Laravel Passport 2.0.0 has been released to provide compatibility with Laravel 5.4 and the Axios[https://github.com/mzabriskie/axios] JavaScript library. If you are upgrading from Laravel 5.3 and using the pre-built Passport Vue components, you should make sure the Axios library is globally available to your application as axios.

Laravel ScoutLaravel Scout

Laravel Scout 3.0.0はLaravel5.4へすでに対応済みです。Laravel Scout 3.0.0 has been released to provide compatibility with Laravel 5.4.

Laravel SocialiteLaravel Socialite

Laravel Socialite 3.0.0はLaravel5.4へすでに対応済みです。Laravel Socialite 3.0.0 has been released to provide compatibility with Laravel 5.4.

Laravel TinkerLaravel Tinker

tinker Artisanコマンドを続けて使用する場合は、laravel/tinkerパッケージもインストールする必要があります。In order to continue using the tinker Artisan command, you should also install the laravel/tinker package:

composer require laravel/tinker

パッケージをインストールしたら、config/app.php設定ファイルのproviders配列へ、Laravel\Tinker\TinkerServiceProvider::classを追加してください。Once the package has been installed, you should add Laravel\Tinker\TinkerServiceProvider::class to the providers array in your config/app.php configuration file.

GuzzleGuzzle

Laravel5.4では、Guzzleのバージョン6.0以上が必要です。Laravel 5.4 requires Guzzle 6.0 or greater.

認証Authorization

getPolicyForメソッドThe getPolicyFor Method

以前のバージョンで、Gate::getPolicyFor($class)メソッドはポリシーが見つからない場合に例外を投げていました。現在、このメソッドは指定クラスのポリシーが見つからない場合、nullを返します。このメソッドを直接呼び出している場合、nullを判定するようにコードをリファクタリングしてください。Previous, when calling the Gate::getPolicyFor($class) method, an exception was thrown if no policy could be found. Now, the method will return null if no policy is found for the given class. If you call this method directly, make sure you refactor your code to check for null:

$policy = Gate::getPolicyFor($class);

if ($policy) {
    // 以前のtryブロックの中のコード
} else {
    // 以前のcatchブロックの中のコード
}

BladeBlade

@sectionエスケープ@section Escaping

セクションに渡されるインラインコンテンツをLaravel5.4は自動的にエスケープします。In Laravel 5.4, inline content passed to a section is automatically escaped:

@section('title', $content)

セクション中のコンテンツをエスケープしないでレンダしたいときは、もとの「長い記法」を使用してください。If you would like to render unescaped content in a section, you must declare the section using the traditional "long form" style:

@section('title')
    {!! $content !!}
@stop

BootstrappersBootstrappers

HTTPとConsoleカーネルの$bootstrappers配列をオーバーライドしている場合は、DetectEnvironmentエントリをLoadEnvironmentVariablesへリネームし、ConfigureLoggingを削除してください。If you are manually overriding the $bootstrappers array on your HTTP or Console kernel, you should rename the DetectEnvironment entry to LoadEnvironmentVariables and remove ConfigureLogging.

ブロードキャストBroadcasting

チャンネルモデル結合Channel Model Binding

Laravel5.3でチャンネル名のプレースフォルダを定義する場合、*文字を使用しました。Laravel5.4では、ルートと同様に{foo}スタイルのプレースホルダを使用し定義してください。When defining channel name placeholders in Laravel 5.3, the * character is used. In Laravel 5.4, you should define these placeholders using {foo} style placeholders, like routes:

Broadcast::channel('App.User.{userId}', function ($user, $userId) {
    return (int) $user->id === (int) $userId;
});

コレクションCollections

everyメソッドThe every Method

everyメソッドの振る舞いは、Lodashにより定義されたメソッド名と一致するように、nthメソッドへ移動しました。The behavior of the every method has been moved to the nth method to match the method name defined by Lodash.

randomメソッドThe random Method

$collection->random(1)の呼び出しは、アイテムを一つ持った新しいコレクションを返すようになりました。以前のこのメソッドは、1オブジェクトを返していました。現在、引数を指定しない場合に1オブジェクトを返します。Calling $collection->random(1) will now return a new collection instance with one item. Previously, this would return a single object. This method will only return a single object if no arguments are supplied.

コンテナContainer

bindinstanceによるエイリアスAliasing Via bind / instance

以前のバージョンのLaravelでは、bindinstanceメソッドの第1引数に、登録するエイリアスを配列で渡しました。In previous Laravel releases, you could pass an array as the first parameter to the bind or instance methods to register an alias:

$container->bind(['foo' => FooContract::class], function () {
    return 'foo';
});

Laravel5.4では、この振る舞いは削除されました。エイリアスを登録するには、aliasメソッドを使用してください。However, this behavior has been removed in Laravel 5.4. To register an alias, you should now use the alias method:

$container->alias(FooContract::class, 'foo');

スラッシュが先頭につく結合クラスBinding Classes With Leading Slashes

スラッシュが先頭に付く結合クラスのコンテナへの登録は、サポートされなくなりました。この機能を実現するために、コンテナ内で数多くの文字列整形を呼び出す必要がありました。シンプルにスラッシュで始まらない結合を登録してください。Binding classes into the container with leading slashes is no longer supported. This feature required a significant amount of string formatting calls to be made within the container. Instead, simply register your bindings without a leading slash:

$container->bind('Class\Name', function () {
    //
});

$container->bind(ClassName::class, function () {
    //
});

makeメソッド引数make Method Parameters

makeメソッドは第2引数に引数の配列を受け取らなくなりました。この機能の使用は、通常悪いコードの印です。通常、より直感的な他の方法でオブジェクトを構築できます。The container's make method no longer accepts a second array of parameters. This feature typically indicates a code smell. Typically, you can always construct the object in another way that is more intuitive.

ResolvingコールバックResolving Callbacks

コンテナのresolvingafterResolvingメソッドは、最初の引数としてクラス名か結合キーを指定する必要があります。The container's resolving and afterResolving method now must be provided a class name or binding key as the first argument to the method:

$container->resolving('Class\Name', function ($instance) {
    //
});

$container->afterResolving('Class\Name', function ($instance) {
    //
});

shareメソッドの削除share Method Removed

shareメソッドはコンテナから削除されました。これは古いメソッドで、数年間ドキュメントに記載されていません。このメソッドを使用しているのであれば、代わりにsingletonメソッドを使ってください。The share method has been removed from the container. This was a legacy method that has not been documented in several years. If you are using this method, you should begin using the singleton method instead:

$container->singleton('foo', function () {
    return 'foo';
});

コンソールConsole

Illuminate\Console\AppNamespaceDetectorTraitトレイトThe Illuminate\Console\AppNamespaceDetectorTrait Trait

直接Illuminate\Console\AppNamespaceDetectorTraitを使用しているのであれば、代わりにIlluminate\Console\AppNamespaceDetectorTraitを使用するようにコードを更新してください。If you are directly referencing the Illuminate\Console\AppNamespaceDetectorTrait trait, update your code to reference Illuminate\Console\DetectsApplicationNamespace instead.

データベースDatabase

カスタム接続Custom Connections

以前のバージョンで、カスタムデータベース接続インスタンスを依存解決するために、サービスコンテナへdb.connection.{ドライバ名}キーを結合していたのであれば、AppServiceProviderregisterメソッドの中で、Illuminate\Database\Connection::resolverForメソッドを呼び出してください。If you were previously binding a service container binding for a db.connection.{driver-name} key in order to resolve a custom database connection instance, you should now use the Illuminate\Database\Connection::resolverFor method in the register method of your AppServiceProvider:

use Illuminate\Database\Connection;

Connection::resolverFor('ドライバ名', function ($connection, $database, $prefix, $config) {
    //
});

フェッチモードFetch Mode

Laravelは設定ファイルからのPDO「フェッチモード」のカスタマイズ機能を提供しなくなりました。代わりに、PDO::FETCH_OBJがいつでも利用できます。アプリケーションのためにフェッチモードを依然カスタマイズするのであれば、新しいIlluminate\Database\Events\StatementPreparedイベントをリッスンしてください。Laravel no longer includes the ability to customize the PDO "fetch mode" from your configuration files. Instead, PDO::FETCH_OBJ is always used. If you would still like to customize the fetch mode for your application you may listen for the new Illuminate\Database\Events\StatementPrepared event:

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});

EloquentEloquent

日付キャストDate Casts

dateキャストはカラムをCarbonオブジェクトに変換するようになり、このオブジェクトのstartOfDayメソッドを呼び出します。日付の時間部分を残したい場合は、datetimeキャストを使用してください。The date cast now converts the column to a Carbon object and calls the startOfDay method on the object. If you would like to preserve the time portion of the date, you should use the datetime cast.

外部キー命名規則Foreign Key Conventions

リレーションの定義時に、外部キーを明確に指定しない場合、Eloquentは関連モデルのテーブル名と主キー名を外部キーの構築に使用するようになりました。ほとんどのアプリケーションでは、これによる振る舞いの変更はありません。例をご覧ください。If the foreign key is not explicitly specified when defining a relationship, Eloquent will now use the table name and primary key name for the related model to build the foreign key. For the vast majority of applications, this is not a change of behavior. For example:

public function user()
{
    return $this->belongsTo(User::class);
}

以前のバージョンのLaravelと同様に、このリレーションは通常外部キーとしてuser_idを使用します。しかし、UserモデルのgetKeyNameメソッドをオーバーライドしている場合は、振る舞いが異なります。例を見てください。Just like previous Laravel releases, this relationship will typically use user_id as the foreign key. However, the behavior could be different from previous releases if you are overriding the getKeyName method of the User model. For example:

public function getKeyName()
{
    return 'key';
}

このケースの場合、Laravelはカスタマイズを尊重するようになり、user_idの代わりにuser_key外部キーカラム名として利用します。When this is the case, Laravel will now respect your customization and determine the foreign key column name is user_key instead of user_id.

BelongsToManyのsetJoinBelongsToMany setJoin

setJoinメソッドは、performJoinへリネームされました。The setJoin method has been renamed to performJoin.

hasOnehasManycreateManyHas One / Many createMany

hasOnehasManyリレーションのcreateManyメソッドは、配列の代わりにコレクションオブジェクトを返すようになりました。The createMany method of a hasOne or hasMany relationship now returns a collection object instead of an array.

関連モデルの接続Related Model Connections

親のモデルと同じ接続を関連するモデルでも使用するようになりました。次のようにクエリを実行できます。Related models will now use the same connection as the parent model. For example, if you execute a query like:

User::on('example')->with('posts');

Eloquentはデフォルトデータベース接続の代わりに、example接続のpostsテーブルをクエリします。デフォルト接続のpostsリレーションを読み込みたい場合は、明確にモデルの接続をアプリケーションのデフォルトへ設定してください。Eloquent will query the posts table on the example connection instead of the default database connection. If you want to read the posts relationship from the default connection, you should to explicitly set the model's connection to your application's default connection.

chunkメソッドThe chunk Method

クエリービルダーのchunkメソッドは、eachメソッドとの一貫性を保つため、orderBy節が必要になりました。orderBy節が指定されていない場合、例外が投げられます。例をご覧ください。The query builder chunk method now requires an orderBy clause, which provides consistency with the each method. An exception will be thrown if an orderBy clause is not supplied. For example:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

Eloquentクエリービルダーのchunkメソッドでは指定されていない場合、orderBy節にモデルの主キーを自動的に適用します。The Eloquent query builder chunk method will automatically apply an orderBy clause on the model's primary key if one is not supplied.

createforceCreateメソッドThe create & forceCreate Methods

複数接続によるモデル生成をより良くサポートするため、Model::createModel::forceCreateIlluminate\Database\Eloquent\Builderへ移動しました。しかし、皆さん自身のモデルの中で、これらのメソッドを拡張している場合は、ビルダーに対しcreateメソッドを呼び出すように、実装を変更する必要があります。The Model::create & Model::forceCreate methods have been moved to the Illuminate\Database\Eloquent\Builder class in order to provide better support for creating models on multiple connections. However, if you are extending these methods in your own models, you will need to modify your implementation to call the create method on the builder. For example:

public static function create(array $attributes = [])
{
    $model = static::query()->create($attributes);

    // ...

    return $model;
}

hydrateメソッドThe hydrate Method

今までこのメソッドにはカスタム接続名を渡していましたが、onメソッドを使うようになりました。If you are currently passing a custom connection name to this method, you should now use the on method:

User::on('connection')->hydrate($records);

hydrateRawメソッドhydrateRaw Method

Model::hydrateRawメソッドはfromQueryへリネームされました。このメソッドへカスタム接続名を渡す場合は、onメソッドを使用してください。The Model::hydrateRaw method has been renamed to fromQuery. If you are passing a custom connection name to this method, you should now use the on method:

User::on('connection')->fromQuery('...');

whereKeyメソッドThe whereKey Method

whereKey($id)メソッドは主キーの値を指定するために"where"節を追加するようになりました。以前のこのメソッドは、動的"where"節ビルダで処理され、"key"カラムへの"where"を追加していました。whereKeyメソッドでkeyカラムへの条件を動的に使っていた場合は、where('key', ...)を変わりに使用してください。The whereKey($id) method will now add a "where" clause for the given primary key value. Previously, this would fall into the dynamic "where" clause builder and add a "where" clause for the "key" column. If you used the whereKey method to dynamically add a condition for the key column you should now use where('key', ...) instead.

factoryヘルパThe factory Helper

factory(User::class, 1)->make()factory(User::class, 1)->create()の呼び出しは、アイテム一つのコレクションを返すようになりました。以前のバージョンでは、モデルを1つ返していました。このメソッドは数を指定しない場合に、モデルを1つ返します。Calling factory(User::class, 1)->make() or factory(User::class, 1)->create() will now return a collection with one item. Previously, this would return a single model. This method will only return a single model if the amount is not supplied.

イベントEvents

Contract ChangesContract Changes

アプリケーションやパッケージで、Illuminate\Contracts\Events\Dispatcherインターフェイスを直接実装している場合は、fireメソッドをdispatchへリネームしてください。If you are manually implementing the Illuminate\Contracts\Events\Dispatcher interface in your application or package, you should rename the fire method to dispatch.

イベントプライオリティEvent Priority

イベントハンドラの「プライオリティ」サポートは削除されました。このドキュメントに記載されていない機能は、通常イベント機能を間違って使用していることを示します。代わりに、同期的にメソッドを順番に呼び出してください。もしくは、イベントハンドラの中から別の新しいイベントをディスパッチしすることで、ハンドラ処理の順番をコントロールしてください。Support for event handler "priorities" has been removed. This undocumented feature typically indicates an abuse of the event feature. Instead, consider using a series of synchronous method calls. Alternatively, you may dispatch a new event from within the handler of another event in order to ensure that a given event's handler fires after an unrelated handler.

ワイルドカードイベントハンドラ使用法Wildcard Event Handler Signatures

ワイルドカードイベントハンドラは、イベント名を最初の引数に、イベントデータを2つ目の引数に受け取るようになりました。Event::firingメソッドは削除されました。Wildcard event handlers now receive the event name as their first argument and the array of event data as their second argument. The Event::firing method has been removed:

Event::listen('*', function ($eventName, array $data) {
    //
});

kernel.handledイベントThe kernel.handled Event

kernel.handledイベントは、オブジェクトベースイベントのIlluminate\Foundation\Http\Events\RequestHandledクラスを使用するようになりました。The kernel.handled event is now an object based event using the Illuminate\Foundation\Http\Events\RequestHandled class.

locale.changedイベントThe locale.changed Event

locale.changedイベントは、オブジェクトベースイベントのIlluminate\Foundation\Events\LocaleUpdatedクラスを使用するようになりました。The locale.changed event is now an object based event using the Illuminate\Foundation\Events\LocaleUpdated class.

illuminate.logイベントThe illuminate.log Event

illuminate.logイベントは、オブジェクトベースイベントのIlluminate\Log\Events\MessageLoggedクラスを使用するようになりました。The illuminate.log event is now an object based event using the Illuminate\Log\Events\MessageLogged class.

例外Exceptions

Illuminate\Http\Exception\HttpResponseExceptionIlluminate\Http\Exceptions\HttpResponseExceptionへリネームされました。Exceptionsと複数形になっていることに注意してください。同様に、Illuminate\Http\Exception\PostTooLargeExceptionIlluminate\Http\Exceptions\PostTooLargeExceptionへリネームされました。The Illuminate\Http\Exception\HttpResponseException has been renamed to Illuminate\Http\Exceptions\HttpResponseException. Note that Exceptions is now plural. Likewise, the Illuminate\Http\Exception\PostTooLargeException has been renamed to Illuminate\Http\Exceptions\PostTooLargeException.

メールMail

クラス@メソッド記法Class@method Syntax

メール送信のクラス@メソッド記法はサポートされなくなりました。Sending mail using Class@method syntax is no longer supported. For example:

Mail::send('view.name', $data, 'クラス@メソッド');

上記のようにメールを送信しているのであれば、Mailableを呼び出すように変更してください。If you are sending mail in this way you should convert these calls to mailables[/docs/{{version}}/mail].

新しい設定オプションNew Configuration Options

Laravel5.4では新しくMarkdownメールコンポーネントをサポートするようになったため、mail設定ファイルの最後に、以下の設定ブロックを追加してください。In order to provide support for Laravel 5.4's new Markdown mail components, you should add the following block of configuration to the bottom of your mail configuration file:

'markdown' => [
    'theme' => 'default',

    'paths' => [
        resource_path('views/vendor/mail'),
    ],
],

クロージャーを使用したメールのキュー投入Queueing Mail With Closures

メールをキューに投入するため、Mailableを使用する必要があります。Mail::queueMail::laterを使用するメールのキューイングには、メールメッセージを設定するためのクロージャは、サポートされなくなりました。PHPはネイティブにクロージャのシリアライズをサポートしていないため、この機能を実現するために特別なライブラリを必要としていました。In order to queue mail, you now must use a mailable[/docs/{{version}}/mail]. Queuing mail using the Mail::queue and Mail::later methods no longer supports using Closures to configure the mail message. This feature required the use of special libraries to serialize Closures since PHP does not natively support this feature.

キューQueue

失敗したジョブのテーブルFailed Jobs Table

アプリケーションが、failed_jobsテーブルを含んでいる場合は、exceptionカラムをそのテーブルへ追加してください。If your application contains a failed_jobs table, you should add an exception column to the table:

$table->longText('exception')->after('payload');

RedisRedis

クラスタサポートの向上Improved Clustering Support

Laravel5.4では、Redisクラスタのサポートが向上しました。Redisクラスタを使用する場合、config/database.php設定ファイルのRedis設定のclustersオプションの中で、クラスタ接続を指定する必要があります。Laravel 5.4 introduces improved Redis cluster support. If you are using Redis clusters, you should place your cluster connections inside of a clusters configuration option in the Redis portion of your config/database.php configuration file:

'redis' => [

    'client' => 'predis',

    'options' => [
        'cluster' => 'redis',
    ],

    'clusters' => [
        'default' => [
            [
                'host' => env('REDIS_HOST', '127.0.0.1'),
                'password' => env('REDIS_PASSWORD', null),
                'port' => env('REDIS_PORT', 6379),
                'database' => 0,
            ],
        ],
    ],

],

ルーティングRouting

PostサイズミドルウェアPost Size Middleware

Illuminate\Foundation\Http\Middleware\VerifyPostSizeクラスは、Illuminate\Foundation\Http\Middleware\ValidatePostSizeへリネームされました。The class Illuminate\Foundation\Http\Middleware\VerifyPostSize has been renamed to Illuminate\Foundation\Http\Middleware\ValidatePostSize.

middlewareメソッドThe middleware Method

Illuminate\Routing\Routerクラスのmiddlewareメソッドは、aliasMiddleware()へリネームされました。HTTPカーネルが$routeMiddleware配列中で定義されている、ルートレベルのミドルウェアを登録するために呼び出しているだけですので、ほとんどのアプリケーションではこのメソッドを直接呼び出すことはないでしょう。The middleware method of the Illuminate\Routing\Router class has been renamed to aliasMiddleware(). It is likely that most applications never call this method manually, as it is typically only called by the HTTP kernel to register route-level middleware defined in the $routeMiddleware array.

RouteメソッドRoute Methods

Illuminate\Routing\RouteクラスのgetUriメソッドは削除されました。uriメソッドを代わりに使用してください。The getUri method of the Illuminate\Routing\Route class has been removed. You should use the uri method instead.

Illuminate\Routing\RouteクラスのgetMethodsメソッドは削除されました。methodsメソッドを代わりに使用してください。The getMethods method of the Illuminate\Routing\Route class has been removed. You should use the methods method instead.

Illuminate\Routing\RouteクラスのgetParameterメソッドは削除されました。parameterメソッドを変わりに使用してください。The getParameter method of the Illuminate\Routing\Route class has been removed. You should use the parameter method instead.

Illuminate\Routing\RouteクラスのgetPathメソッドは削除されました。uriメソッドを代わりに使ってください。The getPath method of the Illuminate\Routing\Route class has been removed. You should use the uri method instead.

セッションSessions

SymfonyコンパチビリティSymfony Compatibility

Laravelのセッションハンドラは、SymfonynのSessionInterfaceを実装しなくなりました。これを実装するとフレームワークで使用しない無関係な機能を実装する必要があるためです。代わりに新しいIlluminate\Contracts\Session\Sessionインターフェイスが定義され、代わりに使用されした。以下の変更も行われました。Laravel's session handlers no longer implements Symfony's SessionInterface. Implementing this interface required us to implement extraneous features that were not needed by the framework. Instead, a new Illuminate\Contracts\Session\Session interface has been defined and may be used instead. The following code changes should also be applied:

->set()メソッドの呼び出しは、全て->put()へ変更してください。ドキュメントに含めていないため、Laravelアプリケーションではsetメソッドを通常呼び出していないでしょう。しかし、注意してください。All calls to the ->set() method should be changed to ->put(). Typically, Laravel applications would never call the set method since it has never been documented within the Laravel documentation. However, it is included here out of caution.

->getToken()メソッドの呼び出しは、全て->token()へ変更してください。All calls to the ->getToken() method should be changed to ->token().

$request->setSession()メソッドの呼び出しは、全てsetLaravelSession()へ変更してください。All calls to the $request->setSession() method should be changed to setLaravelSession().

テストTesting

Laravel5.4のテストレイヤは、より簡単で、より軽くなるように書き直されました。Laravel5.3のテストレイヤを続けて使用したい場合は、アプリケーションにlaravel/browser-kit-testingパッケージをインストールしてください。このパッケージは、Laravel5.3のテストレイヤと完全な互換性があります。実のところ、Laravel5.4のテストレイヤを実行しながら、Laravel5.3テストレイヤも使用できます。Laravel 5.4's testing layer has been re-written to be simpler and lighter out of the box. If you would like to continue using the testing layer present in Laravel 5.3, you may install the laravel/browser-kit-testing package[https://github.com/laravel/browser-kit-testing] into your application. This package provides full compatibility with the Laravel 5.3 testing layer. In fact, you can run the Laravel 5.4 testing layer side-by-side with the Laravel 5.3 testing layer.

Laravel5.4のテストジェネレータを使用し生成した新しいテストを利用するため、Laravelがオートロード可能なように、composer.jsonファイルのautoload-devブロックに、Tests名前空間を追加してください。In order to allow Laravel to autoload any new tests you generate using the Laravel 5.4 test generators, you should add the Tests namespace to your composer.json file's autoload-dev block:

"psr-4": {
    "Tests\": "tests/"
}

同じアプリケーションでLaravel5.3と5.4のテストを実行するRunning Laravel 5.3 & 5.4 Tests In A Single Application

まず、laravel/browser-kit-testingパッケージをインストールします。First install the laravel/browser-kit-testing package:

composer require laravel/browser-kit-testing="1.*" --dev

インストールしたら、tests/TestCase.phpファイルをtestsディレクトリへBrowserKitTestCase.phpとして保存します。それから、Laravel\BrowserKitTesting\TestCaseクラスを拡張するように、このファイルを変更してください。これが終わると、testsディレクトリ下にTestCase.phpBrowserKitTestCase.php、2つのベーステストクラスが用意されます。BrowserKitTestCaseクラスを確実にロードするために、composer.jsonファイルへ追加する必要があります。Once the package has been installed, create a copy of your tests/TestCase.php file and save it to your tests directory as BrowserKitTestCase.php. Then, modify the file to extend the Laravel\BrowserKitTesting\TestCase class. Once you have done this, you should have two base test classes in your tests directory: TestCase.php and BrowserKitTestCase.php. In order for your BrowserKitTestCase class to be properly loaded, you may need to add it to your composer.json file:

"autoload-dev": {
    "classmap": [
        "tests/TestCase.php",
        "tests/BrowserKitTestCase.php"
    ]
},

Laravel5.3上で書かれたテストは、BrowserKitTestCaseクラスを拡張し、Laravel5.4テストレイヤを使用して書かれた新しいテストは、TestCaseクラスを拡張します。BrowserKitTestCaseクラスは以下のようになります。Tests written on Laravel 5.3 will extend the BrowserKitTestCase class while any new tests that use the Laravel 5.4 testing layer will extend the TestCase class. Your BrowserKitTestCase class should look like the following:

<?php

use Illuminate\Contracts\Console\Kernel;
use Laravel\BrowserKitTesting\TestCase as BaseTestCase;

abstract class BrowserKitTestCase extends BaseTestCase
{
    /**
     * アプリケーションのベースURL
     *
     * @var string
     */
    public $baseUrl = 'http://localhost';

    /**
     * アプリケーションの作成
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

このクラスを作成したら、全テストで新しいBrowserKitTestCaseクラスを拡張するように更新してください。これにより、Laravel5.3上で書かれたテストは、続けてLaravel5.4でも実行できるようになります。お望みであれば、少しずつそれらのテストをLaravel5.4記法Laravel Duskへ移行してください。Once you have created this class, make sure to update all of your tests to extend your new BrowserKitTestCase class. This will allow all of your tests written on Laravel 5.3 to continue running on Laravel 5.4. If you choose, you can slowly begin to port them over to the new Laravel 5.4 test syntax[/docs/5.4/http-tests] or Laravel Dusk[/docs/5.4/dusk].

Note: note 新しいテストを書き、Laravel5.4テストレイヤで使用する場合は、確実にTestCaseクラスを拡張してください。{note} If you are writing new tests and want them to use the Laravel 5.4 testing layer, make sure to extend the TestCase class.

アップデート済みアプリケーションへのDuskインストールInstalling Dusk In An Upgraded Application

Laravel5.3からアップグレードしたアプリケーションに、Laravel Duskをインストールしたい場合は、最初にComposerを使用し、インストールします。If you would like to install Laravel Dusk into an application that has been upgraded from Laravel 5.3, first install it via Composer:

composer require laravel/dusk

次に、testsディレクトリ下にCreatesApplicationトレイトを作成する必要があります。このトレイトはテストケースに対して、真新しいアプリケーションインスタンスを生成することに責任を負います。このトレイトは次のような内容です。Next, you will need to create a CreatesApplication trait in your tests directory. This trait is responsible for creating fresh application instances for test cases. The trait should look like the following:

<?php

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * アプリケーションの作成
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

Note: note テストに名前空間を付けており、testsディレクトリのロードにPSR-4オートロード規約を使用してい場合は、適切な名前空間下にCreatesApplicationトレイトを設置してください。{note} If you have namespaced your tests and are using the PSR-4 autoloading standard to load your tests directory, you should place the CreatesApplication trait under the appropriate namespace.

これらの手順をやり終えたら、通常通りのDuskインストール手順に従ってください。Once you have completed these preparatory steps, you can follow the normal Dusk installation instructions[/docs/{{version}}/dusk#installation].

環境Environment

Laravel5.4テストクラスは、各テストごとにputenv('APP_ENV=testing')を共用しなくなりました。代わりにフレームワークは、読み込んだ.envファイルのAPP_ENV変数を使用します。The Laravel 5.4 test class no longer manually forces putenv('APP_ENV=testing') for each test. Instead, the framework utilizes the APP_ENV variable from the loaded .env file.

Event FakeEvent Fake

Event FakeのassertFiredメソッドはassertDispatchedへ、assertNotFiredメソッドはassertNotDispatchedへ変更してください。メソッドの使い方に変更はありません。The Event fake's assertFired method should be updated to assertDispatched, and the assertNotFired method should be updated to assertNotDispatched. The method's signatures have not been changed.

Mail FakeMail Fake

Laravel5.4で、Mail Fakeはとても簡略化されました。assertSentToメソッドを使用する代わりに、assertSentメソッドを使用し、hasTohasCcなどのヘルパメソッドをコールバック内で使用してください。The Mail fake has been greatly simplified for the Laravel 5.4 release. Instead of using the assertSentTo method, you should now simply use the assertSent method and utilize the hasTo, hasCc, etc. helper methods within your callback:

Mail::assertSent(MailableName::class, function ($mailable) {
    return $mailable->hasTo('email@example.com');
});

翻訳Translation

{Inf}プレースホルダ{Inf} Placeholder

{Inf}を翻訳文字列の複数形に対するプレースホルダとして使用している場合は、代わりに*文字を使用するように翻訳文字列を変更してください。If you are using the {Inf} placeholder for pluralizing your translation strings, you should update your translation strings to use the * character instead:

{0} First Message|{1,*} Second Message

transヘルパThe trans Helpers

transヘルパの使用法は、不必要な$domain引数を削除するように変更されました。新しい引数は以下のとおりです。The trans helper signature has been updated to remove the unnecessary $domain argument. The new signature is as follows:

/**
 * 指定メッセージの翻訳
 *
 * @param  string  $id
 * @param  array   $replace
 * @param  string  $locale
 * @return \Illuminate\Contracts\Translation\Translator|string|array|null
 */
function trans($id = null, $replace = [], $locale = null);

また、trans_choiceヘルパも変更されました。In addition, the trans_choice helper has been updated:

/**
 * Translates the given message based on a count.
 *
 * @param  string  $id
 * @param  int|array|\Countable  $number
 * @param  array   $replace
 * @param  string  $locale
 * @return string
 */
function trans_choice($id, $number, array $replace = [], $locale = null);

URL生成URL Generation

forceSchemaメソッドThe forceSchema Method

Illuminate\Routing\UrlGeneratorクラスのforceSchemaメソッドは、forceSchemeへリネームされました。The forceSchema method of the Illuminate\Routing\UrlGenerator class has been renamed to forceScheme.

バリデーションValidation

日付フォーマットのバリデーションDate Format Validation

日付フォーマットのバリデーションはより厳格になり、PHPの日付関数のドキュメント内に記載のあるプレースホルダをサポートしました。以前のバージョンのLaravelでは、タイムゾーンのプレースホルダであるPは全タイムゾーンフォーマットを受け付けていました。しかし、Laravel5.4ではPHPドキュメントに従い、それぞれのタイムゾーンフォーマットごとに独自のプレースホルダを指定してください。Date format validation is now more strict and supports the placeholders present within the documentation for the PHP date function[http://php.net/manual/en/function.date.php]. In previous releases of Laravel, the timezone placeholder P would accept all timezone formats; however, in Laravel 5.4 each timezone format has a unique placeholder as per the PHP documentation.

メソッド名Method Names

addErrorメソッドはaddFailureへリネームされました。更に、doReplacementsメソッドもmakeReplacementsへリネームされました。通常、これらの変更はValidatorクラスを拡張している場合に影響します。The addError method has been renamed to addFailure. In addition, the doReplacements method has been renamed to makeReplacements. Typically, these changes will only be relevant if you are extending the Validator class.

その他Miscellaneous

laravel/laravel GitHubリポジトリで、変更を確認することもおすすめします。それらの多くの変更は必要ないでしょうが、皆さんのアプリケーションで同期を保ちたいでしょう。変更の一部はこのアップグレードガイドに記載されていますが、設定ファイルやコメントなどの変更は乗っていません。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/5.3...master] 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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作