5.2から5.3.0へのアップグレードUpgrading To 5.3.0 From 5.2
アップデート見積もり時間:2時間から3時間Estimated Upgrade Time: 2-3 Hours
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.3.*
へアップデートしてください。Update your
laravel/framework
dependency to
5.3.*
in your
composer.json
file.
さらに、composer.json
ファイルのrequire-dev
セクションにある、symfony/css-selector
とsymfony/dom-crawler
の依存を3.1.*
にアップグレードしてください。You should also upgrade your
symfony/css-selector
and
symfony/dom-crawler
dependencies to
3.1.*
in the require-dev
section of your composer.json
file.
PHPとHHVMPHP & HHVM
Laravel5.3はPHP5.6.4以上が必要です。HHVMは公式にサポートされなくなりました。PHP5.6以降と同じ言語機能を含んでいないためです。Laravel 5.3 requires PHP 5.6.4 or higher. HHVM is no longer officially supported as it does not contain the same language features as PHP 5.6 .
非推奨Deprecations
Laravel 5.2アップグレードガイドにリストされていた非推奨の機能はすべて、フレームワークから取り除かれました。このリストを見直し、これらの非推奨機能を既に使用していないことを確認してください。All of the deprecations listed in the Laravel 5.2 upgrade guide[#5.2-deprecations] have been removed from the framework. You should review this list to verify you are no longer using these deprecated features.
アプリケーションサービスプロバイダApplication Service Providers
EventServiceProvider
、RouteServiceProvider
、RouteServiceProvider
クラスのboot
メソッドから引数を取り除いてください。渡された引数の呼び出しは、同じ機能のfacadeを代わりに置き換えて、使用してください。たとえば、$dispatcher
引数のメソッドを呼び出す代わりに、Event
ファサードをシンプルに呼び出してください。同様に、$router
引数のメソッド呼び出しの代わりに、Route
ファサードを呼び出してください。$gate
引数を呼び出す代わりに、Gate
ファサードを呼び出してください。You may remove the arguments from
the boot
method on the
EventServiceProvider
,
RouteServiceProvider
, and
AuthServiceProvider
classes. Any calls
to the given arguments may be converted to use the
equivalent facade[/docs/5.3/facades] instead.
So, for example, instead of calling methods on the
$dispatcher
argument, you may simply
call the Event
facade. Likewise,
instead of making method calls to the
$router
argument, you may make calls to
the Route
facade, and instead of making
method calls to the $gate
argument, you
may make calls to the Gate
facade.
Note: {note} When converting method calls to facades, be sure to import the facade class into your service provider.
メソッド呼び出しをファサードへ書き換える際は、サービスプロバイダでそのファサードを確実にインポートしてください。
配列Arrays
キー/値順序変更Key / Value Order Change
Arr
クラスのfirst
、last
、where
メソッドに渡すクロージャの、最初の引数として「値」が渡されます。例をご覧ください。The first
,
last
, and where
methods on
the Arr
class now pass the
"value" as the first parameter to the
given callback Closure. For example:
Arr::first($array, function ($value, $key) {
return ! is_null($value);
});
以前のバージョンのLaravelでは、$key
が最初に渡されていました。ほとんどのユースケースでは、$value
だけに関心がありますので、最初に渡るようになりました。アプリケーション「全体を検索」して、これらのメソッドを見つけ、クロージャの最初の引数として$value
を受け取ることを確認してください。In previous versions of Laravel,
the $key
was passed first. Since most
use cases are only interested in the
$value
it is now passed first. You
should do a "global find" in your
application for these methods to verify that you are
expecting the $value
to be passed as
the first argument to your Closure.
ArtisanArtisan
make:console
コマンドThe make:console
Command
make:console
コマンドは、make:command
へ名前が変更になりました。The make:console
command has been renamed to
make:command
.
認証Authentication
認証スカフォールドAuthentication Scaffolding
フレームワークが提供する2つの認証コントローラは、4つの小さなコントローラへと分割されました。この変更によりデフォルトでも、きれいで、役割に集中したコントローラになりました。アプリケーションを新しいコントローラへアップグレードする一番簡単な方法は、GitHubから真新しい各コントローラをコピーし、アプリケーションに設置してください。The two default authentication controllers provided with the framework have been split into four smaller controllers. This change provides cleaner, more focused authentication controllers by default. The easiest way to upgrade your application to the new authentication controllers is to grab a fresh copy of each controller from GitHub[https://github.com/laravel/laravel/tree/5.3/app/Http/Controllers/Auth] and place them into your application.
さらに、routes/web.php
ファイルの中で、Auth::routes()
メソッドを確実に呼び出してください。このメソッドは、新しい認証コントローラのルートを確実に登録します。You should also make sure that
you are calling the Auth::routes()
method in your routes/web.php
file.
This method will register the proper routes for the
new authentication controllers.
アプリケーションに新しいコントローラを設置できたら、もとのコントローラに対して行ったカスタマイズを再実装する必要があります。たとえば、認証に使用する認証ガードをカスタマイズしていたら、コントローラのguard
メソッドをオーバーライドする必要があります。どのメソッドをオーバーライドすればよいのかを決めるため、認証コントローラのトレイトの内容を調べてください。Once these controllers have been
placed into your application, you may need to
re-implement any customizations you made to these
controllers. For example, if you are customizing the
authentication guard that is used for
authentication, you may need to override the
controller's guard
method. You can
examine each authentication controller's trait to
determine which methods to override.
">Tip!! 認証コントローラをカスタマイズしていない場合は、GitHubから新しいコントローラをコピー、設置し、
routes/web.php
ファイルでAuth::routes
メソッドを呼び出すだけです。{tip} If you were not customizing the authentication controllers, you should just be able to drop in fresh copies of the controllers from GitHub and verify that you are calling theAuth::routes
method in yourroutes/web.php
file.
パスワードリセットメールPassword Reset Emails
パスワードリセットはLaravelの新しい通知機能を使っています。パスワードリセットリンクを送る時に、通知を送るようにカスタマイズしたい場合は、Illuminate\Auth\Passwords\CanResetPassword
トレイトのsendPasswordResetNotification
メソッドをオーバーライドしてください。Password reset emails now use the new
Laravel notifications feature. If you would like to
customize the notification sent when sending password reset
links, you should override the
sendPasswordResetNotification
method of the
Illuminate\Auth\Passwords\CanResetPassword
trait.
パスワードリセットリンクメールを送るために、User
モデルで新しいIlluminate\Notifications\Notifiable
トレイトをuseする必要があります。Your User
model
must use the new
Illuminate\Notifications\Notifiable
trait in
order for password reset link emails to be
delivered:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
}
Note:
config/app.php
設定ファイルの、providers
配列へ、Illuminate\Notifications\NotificationServiceProvider
を登録し忘れないでください。{note} Don't forget to register theIlluminate\Notifications\NotificationServiceProvider
in theproviders
array of yourconfig/app.php
configuration file.
ログアウトのためのPOSTPOST To Logout
Auth::routes
メソッドは/logout
のルートをGET
の代わりにPOST
として登録するようになりました。これにより、他のWebアプリケーションが皆さんのアプリケーションからユーザをログアウトするのを防ぎます。アップグレードするには、ログアウトリクエストでPOST
動詞を使用するように変更するか、自身の/logout
URIに対するGET
ルートを登録してください。The
Auth::routes
method now registers a
POST
route for /logout
instead of
a GET
route. This prevents other web
applications from logging your users out of your
application. To upgrade, you should either convert your
logout requests to use the POST
verb or
register your own GET
route for the
/logout
URI:
Route::get('/logout', 'Auth\LoginController@logout');
認証Authorization
ポリシーメソッドの呼び出し時のクラス名Calling Policy Methods With Class Names
いくつかのポリシーメソッドでは、現在認証済みユーザを受け取りますが、認可するモデルのインスタンスを必要としません。この状況はcreate
アクションの認証時が一番顕著に起きます。たとえば、あなたがブログを作成している場合、どんなポストでも作成できる認可を持つユーザであるかをチェックしたいと思うことでしょう。Some policy methods only receive the
currently authenticated user and not an instance of the
model they authorize. This situation is most common when
authorizing create
actions. For example, if you
are creating a blog, you may wish to check if a user is
authorized to create any posts at all.
モデルインスタンスを受け取らない、create
メソッドのようなポリシーメソッドを定義する時に、メソッドの第2引数としてクラス名は渡されなくなりました。メソッドは認証ユーザインスタンスだけを受け取るようにしなくてはなりません。When defining policy methods that will
not receive a model instance, such as a create
method, the class name will no longer be passed as the
second argument to the method. Your method should just
expect the authenticated user instance:
/**
* 指定されたユーザがポストを作成できるか判断する
*
* @param \App\User $user
* @return bool
*/
public function create(User $user)
{
//
}
AuthorizesResources
トレイトThe
AuthorizesResources
Trait
AuthorizesResources
トレイトは、AuthorizesRequests
トレイトにマージされました。app/Http/Controllers/Controller.php
ファイルから、AuthorizesResources
トレイトを削除してください。The AuthorizesResources
trait has been merged with the
AuthorizesRequests
trait. You should remove the
AuthorizesResources
trait from your
app/Http/Controllers/Controller.php
file.
BladeBlade
カスタムDirectivesCustom Directives
以前のバージョンのLaravelでは、directive
メソッドを使い、カスタムBladeディレクティブを登録したとき、一番外側のカッコの内容を含む$expression
がディレクティブのコールバックに渡されていました。Laravel5.3では、ディレクティブのコールバックに、一番外側のカッコは渡されません。Blade拡張のドキュメントを確認し、皆さんのカスタムBlaseディレクティブが確実に動作するかを確認してください。In prior versions of Laravel, when
registering custom Blade directives using the
directive
method, the $expression
passed to your directive callback contained the outer-most
parenthesis. In Laravel 5.3, these outer-most parenthesis
are not included in the expression passed to your directive
callback. Be sure to review the Blade
extension[/docs/5.3/blade#extending-blade]
documentation and verify your custom Blade directives are
still working properly.
ブロードキャストBroadcasting
サービスプロバイダService Provider
Laravel5.3のイベントブロードキャストは大きな進歩をしました。 ファイル内容をGitHubで確認し、app/Providers
ディレクトリに新しいBroadcastServiceProvider
を追加してください。新しいサービスプロバイダが定義できたら、config/app.php
設定ファイルのproviders
配列へ追加してください。Laravel 5.3 includes significant
improvements to event
broadcasting[/docs/{{version}}/broadcasting]. You
should add the new BroadcastServiceProvider
to
your app/Providers
directory by grabbing a
fresh copy of the source from
GitHub[https://raw.githubusercontent.com/laravel/laravel/5.3/app/Providers/BroadcastServiceProvider.php].
Once you have defined the new service provider, you should
add it to the providers
array of your
config/app.php
configuration file.
キャッシュCache
拡張のクロージャ結合と$this
Extension
Closure Binding & $this
Cache::extend
メソッドをクロージャと一緒に呼び出す時、$this
はCacheManager
インスタンスと結合されていますので、クロージャの中からメソッドを呼び出すことができます。When calling the
Cache::extend
method with a Closure,
$this
will be bound to the
CacheManager
instance, allowing you to call its
methods from within your extension Closure:
Cache::extend('memcached', function ($app, $config) {
try {
return $this->createMemcachedDriver($config);
} catch (Exception $e) {
return $this->createNullDriver($config);
}
});
CashierCashier
Cashierを使っている場合は、laravel/cashier
パッケージを~7.0
のリリースにアップグレードしてください。このCashierのリリースでは、Laravel5.3と互換性のある内部メソッドをいくつかアップグレードしていますが、互換性を崩す変更はありません。If you are using Cashier, you should
upgrade your laravel/cashier
package to the
~7.0
release. This release of Cashier only
upgrades a few internal methods to be compatible with
Laravel 5.3 and is not a breaking change.
コレクションCollections
キー/値順の変更Key / Value Order Change
first
、last
、contains
コレクションメソッドでは、指定されたコールバッククロージャの第1引数に「値」が渡されます。例をご覧ください。The first
,
last
, and contains
collection
methods all pass the "value" as the first
parameter to their given callback Closure. For
example:
$collection->first(function ($value, $key) {
return ! is_null($value);
});
以前のLaravelでは$key
が最初に渡されていました。ほとんどのケースでは$value
にのみ関心がありますので、今回から最初に渡しています。これらのメソッドをアプリケーション「全体に対し検索」し、クロージャの第1引数に$value
が渡されるように修正してください。In previous versions of Laravel, the
$key
was passed first. Since most use cases are
only interested in the $value
it is now passed
first. You should do a "global find" in your
application for these methods to verify that you are
expecting the $value
to be passed as the first
argument to your Closure.
コレクションwhere
はデフォルトで「緩い」比較方法へCollection where
Comparison
Methods Are "Loose" By Default
コレクションのwhere
メソッドのデフォルト比較方法が、厳格な比較から、「緩い」比較になりました。厳格な比較をしたい場合は、whereStrict
メソッドを使ってください。A collection's where
method
now performs a "loose" comparison by default
instead of a strict comparison. If you would like to perform
a strict comparison, you may use the
whereStrict
method.
さらに、where
メソッドは「厳格さ」を表す第3パラメータを取らなくアンリました。アプリケーションの必要性に応じて、where
かwhereStrict
を明確に呼び出してください。The where
method also no
longer accepts a third parameter to indicate
"strictness". You should explicitly call either
where
or whereStrict
depending on
your application's needs.
設定Configuration
アプリケーション名Application Name
config/app.php
設定ファイルの中に、以下の設定オプションを追加してください。In the config/app.php
configuration file, add the following configuration
option:
'name' => 'アプリケーション名',
コントローラControllers
コンストラクタ中のセッションSession In The Constructor
以前のバージョンのLaravelでは、コントローラのコンストラクタでセッション変数や認証族ユーザにアクセスできました。これはフレームワークの機能として、明確に意図したものではありません。Laravel5.3では、セッションや認証済みユーザにコントローラのコンストラクタではアクセスできません。なぜなら、ミドルウェアがまだ実行されていないからです。In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
代わりに、クロージャベースのミドルウェアをコントローラのコンストラクタで直接で意義できます。この機能を使用する前に、アプリケーションがLaravel5.3.4
以上で実行されていることを確認してください。As an alternative, you may define a
Closure based middleware directly in your controller's
constructor. Before using this feature, make sure that your
application is running Laravel 5.3.4
or
above:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class ProjectController extends Controller
{
/**
* 現在のユーザの全プロジェクト
*/
protected $projects;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
return $next($request);
});
}
}
もちろん、コントローラアクションで、Illuminate\Http\Request
クラスをタイプヒントで指定することで、リクエストセッションデータや認証済みユーザへアクセスすることもできます。Of course, you may also access the
request session data or authenticated user by type-hinting
the Illuminate\Http\Request
class on your
controller action:
/**
* 現在のユーザの全プロジェクトを表示
*
* @param \Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
$projects = $request->user()->projects;
$value = $request->session()->get('key');
//
}
データベースDatabase
コレクションCollections
Fluentなクエリビルダが普通の配列の代わりに、Illuminate\Support\Collection
インスタンスを返すようになりました。これに予知、クエリビルダとEloquentにより返されるタイプに一貫性がもたらされました。The fluent query
builder[/docs/{{version}}/queries] now returns
Illuminate\Support\Collection
instances instead
of plain arrays. This brings consistency to the result types
returned by the fluent query builder and
Eloquent.
もし、クエリビルダの結果をCollection
インスタンスにしたくない場合は、クエリビルダのget
やpluck
メソッドにall
メソッドをチェーンしてください。これにより、結果としてプレーンな配列が返され、後方互換生が保てます。If you do not want to migrate your query
builder results to Collection
instances, you
may chain the all
method onto your calls to the
query builder's get
or pluck
methods. This will return a plain PHP array of the results,
allowing you to maintain backwards compatibility:
$users = DB::table('users')->get()->all();
$usersIds = DB::table('users')->pluck('id')->all();
Eloquent のgetRelation
メソッドEloquent getRelation
Method
EloquentのgetRelation
メソッドは、リレーションをロードできない場合にBadMethodCallException
を投げなくなりました。代わりにIlluminate\Database\Eloquent\RelationNotFoundException
が投げられるようになりました。この変更は、BadMethodCallException
をあなたのソースコード中でキャッチしている場合のみ、影響があります。The Eloquent getRelation
method no longer throws a
BadMethodCallException
if the relation can't be
loaded. Instead, it will throw an
Illuminate\Database\Eloquent\RelationNotFoundException
.
This change will only affect your application if you were
manually catching the
BadMethodCallException
.
Eloquentの$morphClass
プロパティEloquent $morphClass
Property
Eloquentモデルで定義されていた、「morphマップ」を定義するための$morphClass
プロパティーは削除されました。以前サポートされていたmorphマップの定義は、Eagerローディングをサポートし、ポリモーフィックリレーションの余計なバグを解決するために提供されていました。以前の$morphClass
プロパティを使用していたばあい、以下の記法によりmorphMap
へ切り替える必要があります。The $morphClass
property
that could be defined on Eloquent models has been removed in
favor of defining a "morph map". Defining a morph
map provides support for eager loading and resolves
additional bugs with polymorphic relations. If you were
previously relying on the $morphClass
property,
you should migrate to morphMap
using the
following syntax:
Relation::morphMap([
'YourCustomMorphName' => YourModel::class,
]);
たとえば、もしこれまで次のような$morphClass
を定義をしていたら:For example, if you previously defined
the following $morphClass
:
class User extends Model
{
protected $morphClass = 'user'
}
AppServiceProvider
のboot
メソッドで、以下のようにmorphMap
を定義する必要があります。You should define the following
morphMap
in the boot
method of
your AppServiceProvider
:
use Illuminate\Database\Eloquent\Relations\Relation;
Relation::morphMap([
'user' => User::class,
]);
EloquentのScopesEloquent Scopes
Eloquentのスコープでは、先頭の論理型スコープ制約を尊重するようになりました。たとえば、スコープをorWhere
制約で始めたとしても、通常のwhere
へ変更されなくなります。この機能を使用していた場合(たとえば、ループの中で複数のorWhere
をついかするなど)、論理型ロジックの問題を引き起こさないように、最初の条件は通常のwhere
で始めるようにしてください。Eloquent scopes now respect the leading
boolean of scope constraints. For example, if you are
starting your scope with an orWhere
constraint
it will no longer be converted to normal where
.
If you were relying on this feature (e.g. adding multiple
orWhere
constraints within a loop), you should
verify that the first condition is a normal
where
to avoid any boolean logic
issues.
where
制約でスコープを始めている場合、変更はありません。クエリのtoSql
メソッドを使えば、クエリのSQLを確認できることを思い出してください。If your scopes begin with
where
constraints no action is required.
Remember, you can verify your query SQL using the
toSql
method of a query:
User::where('foo', 'bar')->toSql();
Join節Join Clause
JoinClause
クラスはクエリビルだと記法を統一するために書き直されました。on
節のオプション$where
パラメータは削除されました。クエリビルダで行うように、"where"条件を追加したい場合は、明確に一つのwhere
メソッドを使用してください。The JoinClause
class has
been rewritten to unify its syntax with the query builder.
The optional $where
parameter of the
on
clause has been removed. To add a
"where" conditions you should explicitly use one
of the where
methods offered by the query
builder[/docs/{{version}}/queries#where-clauses]:
$query->join('table', function ($join) {
$join->on('foo', 'bar')->where('bar', 'baz');
});
on
節のオペレータはバリデートされるようになり、不正な値を含めなくなりました。もしこの機能たとえば、$join->on('foo',
'in',
DB::raw('("bar")'))
)に頼っている場合は、正しいWHERE節を使用し、条件を書き直してください。The operator of the on
clause is now validated and can no longer contain invalid
values. If you were relying on this feature (e.g.
$join->on('foo', 'in',
DB::raw('("bar")'))
) you should rewrite
the condition using the appropriate where clause:
$join->whereIn('foo', ['bar']);
$binding
プロパティも削除されました。JOIN結合操作には、直接addBinding
メソッドを使用してください。The $bindings
property was
also removed. To manipulate join bindings directly you may
use the addBinding
method:
$query->join(DB::raw('('.$subquery->toSql().') table'), function ($join) use ($subquery) {
$join->addBinding($subquery->getBindings(), 'join');
});
暗号化Encryption
Mcrypt暗号化クラスの削除Mcrypt Encrypter Has Been Removed
Mcrypt暗号化クラスは2015年6月にリリースされたLaravel5.1.0から非推奨になっていました。Laravel5.1.0以降の全リリースでデフォルト暗号化スキームとなっている、OpenSSLに基づいたより新しい暗号化実装が導入されているため、この暗号化クラスは5.3.0リリースで完全に削除されました。The Mcrypt encrypter was deprecated during the Laravel 5.1.0 release in June 2015. This encrypter has been totally removed in the 5.3.0 release in favor of the newer encryption implementation based on OpenSSL, which has been the default encryption scheme for all releases since Laravel 5.1.0.
Mcryptベースのcipher
をまだ使用している場合は、config/app.php
設定ファイルで、cipherをAES-256-CBC
に更新し、php
artisan
key:generate
で生成できるセキュアな32バイトのランダム文字列をキーとして設定してください。If you are still using an Mcrypt based
cipher
in your config/app.php
configuration file, you should update the cipher to
AES-256-CBC
and set your key to a random 32
byte string which may be securely generated using php
artisan key:generate
.
Mcryptの暗号化クラスを使用し、暗号化したデータをデータベースへ保存している場合は、レガシーなMcrypt暗号化クラスの実装を含んでいる、laravel/legacy-encrypter
packageをインストールしてください。このパッケージで暗号化されたデータを複合し、新しいOpenSSL暗号化クラスを使って再度暗号化してください。たとえば、次のようなカスタムArtisanコマンドで実行できます。If you are storing encrypted data in your
database using the Mcrypt encrypter, you may install the
laravel/legacy-encrypter
package[https://github.com/laravel/legacy-encrypter]
which includes the legacy Mcrypt encrypter implementation.
You should use this package to decrypt your encrypted data
and re-encrypt it using the new OpenSSL encrypter. For
example, you may do something like the following in a
custom Artisan
command[/docs/{{version}}/artisan]:
$legacy = new McryptEncrypter($encryptionKey);
foreach ($records as $record) {
$record->encrypted = encrypt(
$legacy->decrypt($record->encrypted)
);
$record->save();
}
例外ハンドラException Handler
コンストラクタConstructor
ベース例外ハンドラクラスは、Illuminate\Container\Container
インスタンスをコンストラクタで受け取ります。この変更はアプリケーションでカスタム__construct
メソッドをapp/Exceptions/Handler.php
ファイル中で定義している場合のみ、影響を与えます。これを定義しているばあい、コンテナインスタンスをparent::__construct
メソッドに渡す必要があります。The base exception handler class now
requires a Illuminate\Container\Container
instance to be passed to its constructor. This change will
only affect your application if you have defined a custom
__construct
method in your
app/Exceptions/Handler.php
file. If you have
done this, you should pass a container instance into the
parent::__construct
method:
parent::__construct(app());
UnauthenticatedメソッドUnauthenticated Method
App\Exceptions\Handler
クラスへ、unauthenticated
メソッドを追加してください。このメソッドは、認証の例外をHTTPレスポンスへ変換します。You should add the
unauthenticated
method to your
App\Exceptions\Handler
class. This method will
convert authentication exceptions into HTTP
responses:
/**
* 認証例外を非認証レスポンスへ変換する
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
ミドルウェアMiddleware
can
ミドルウェア名前空間変更can
Middleware Namespace
Change
HTTPカーネルの$routeMiddleware
プロパティにリストされている、can
ミドルウェアは以下のクラスへアップデートしてください。The can
middleware listed in
the $routeMiddleware
property of your HTTP
kernel should be updated to the following class:
'can' => \Illuminate\Auth\Middleware\Authorize::class,
can
ミドルウェア認証例外can
Middleware
Authentication Exception
can
ミドルウェアは、ユーザが認証されていない場合に、Illuminate\Auth\AuthenticationException
のインスタンスを投げるようになりました。もし、自分で異なった例外タイプを補足している場合は、アプリケーションでこの例外をキャッチするように変更してください。ほとんどの場合は、これはアプリケーションに影響を与えません。The can
middleware will now
throw an instance of
Illuminate\Auth\AuthenticationException
if the
user is not authenticated. If you were manually catching a
different exception type, you should update your application
to catch this exception. In most cases, this change will not
affect your application.
モデル結合ミドルウェアBinding Substitution Middleware
Routeモデル結合はミドルウェアで実行されるようになりました。全アプリケーションで、app/Http/Kernel.php
ファイルのweb
ミドルウェアグループに、Illuminate\Routing\Middleware\SubstituteBindings
を追加する必要があります。Route model binding is now accomplished
using middleware. All applications should add the
Illuminate\Routing\Middleware\SubstituteBindings
to your web
middleware group in your
app/Http/Kernel.php
file:
\Illuminate\Routing\Middleware\SubstituteBindings::class,
さらに、モデル結合のルートミドルウェアをHTTPカーネルの$routeMiddleware
プロパティで登録する必要があります。You should also register a route
middleware for binding substitution in the
$routeMiddleware
property of your HTTP
kernel:
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
このミドルウェアが登録できたら、api
ミドルウェアグループを追加してください。Once this route middleware has been
registered, you should add it to the api
middleware group:
'api' => [
'throttle:60,1',
'bindings',
],
通知Notifications
インストールInstallation
Laravel5.3には新しい、ドライバベースの通知システムが用意されました。config/app.php
設定ファイルのProviders
配列に、Illuminate\Notifications\NotificationServiceProvider
を登録してください。Laravel 5.3 includes a new, driver based
notification system. You should register the
Illuminate\Notifications\NotificationServiceProvider
in the providers
array of your
config/app.php
configuration file.
さらに、config/app.php
設定ファイルのaliases
配列へIlluminate\Support\Facades\Notification
ファサードを追加します。You should also add the
Illuminate\Support\Facades\Notification
facade
to the aliases
array of your
config/app.php
configuration file.
最後に、Illuminate\Notifications\Notifiable
トレイトをUser
モデルや他の通知を受け取りたいモデルでuseしてください。Finally, you may use the
Illuminate\Notifications\Notifiable
trait on
your User
model or any other model you wish to
receive notifications.
ペジネーションPagination
カスタマイズCustomization
Laravel5.3でのペジネータが生成するHTMLのカスタマイズは、以前のLaravel5.xリリースに比べ、より簡単になっています。"Presenter"クラスを定義する代わりに、シンブルなBladeテンプレートを定義するだけです。ペジネーションビューをカスタマイズする簡単な方法は、vendor:publish
コマンドを使い、resources/views/vendor
ディレクトリにビューを作成することです。Customizing the paginator's generated
HTML is much easier in Laravel 5.3 compared to previous
Laravel 5.x releases. Instead of defining a
"Presenter" class, you only need to define a
simple Blade template. The easiest way to customize the
pagination views is by exporting them to your
resources/views/vendor
directory using the
vendor:publish
command:
php artisan vendor:publish --tag=laravel-pagination
このコマンドにより、ビューがresources/views/vendor/pagination
ディレクトリに用意されます。このディレクトリのdefault.blade.php
ファイルが、デフォルトペジネーションビューへ対応しています。ペジネーションHTMLを変更するには、このファイルを編集するだけです。This command will place the views in the
resources/views/vendor/pagination
directory.
The default.blade.php
file within this
directory corresponds to the default pagination view. Simply
edit this file to modify the pagination HTML.
ペジネーションのドキュメントで完全な情報を確認してください。Be sure to review the full pagination documentation[/docs/{{version}}/pagination] for more information.
キューQueue
設定Configuration
キュー設定の中の、全expire
設定アイテムは、retry_after
ヘリネームしてください。同様に、Beanstalk設定のttr
アイテムも、retry_after
へリネームします。この名前変更により、この設定オプションの目的がよりクリアになります。In your queue configuration, all
expire
configuration items should be renamed to
retry_after
. Likewise, the Beanstalk
configuration's ttr
item should be renamed to
retry_after
. This name change provides more
clarity on the purpose of this configuration
option.
クロージャClosures
クロージャのキュー投入はサポートされなくなりました。アプリケーションでクロージャをキューイングしたい場合は、クロージャをクラスへ変換し、そのクラスのインスタンスをキューしてください。Queueing Closures is no longer supported. If you are queueing a Closure in your application, you should convert the Closure to a class and queue an instance of the class:
dispatch(new ProcessPodcast($podcast));
コレクションのサニタライズCollection Serialization
Illuminate\Queue\SerializesModels
トレイトが、正しくIlluminate\Database\Eloquent\Collection
のインスタンスをシリアライズするようになりました。これにより、アプリケーションの大多数で、互換性を崩すような変更は起きていないと思われます。しかしながら、キュー済みのジョブがデータベースから再取得しないコレクションに依存している場合は、この変更がアプリケーションへ悪影響を起こさないことを確認してください。The
Illuminate\Queue\SerializesModels
trait now
properly serializes instances of
Illuminate\Database\Eloquent\Collection
. This
will most likely not be a breaking change for the vast
majority of applications; however, if your application is
absolutely dependent on collections not being re-retrieved
from the database by queued jobs, you should verify that
this change does not negatively affect your
application.
デーモンワーカDaemon Workers
queue:work
Artisanコマンドを呼び出す時に、--daemon
オプションの指定は必要なくなりました。php
artisan
queue:work
コマンドが自動的にデーモンモードでワーカを実行したがっていると仮定します。ジョブを一つ処理したい場合は、--once
オプションをコマンドにつけてください。It is no longer necessary to specify the
--daemon
option when calling the
queue:work
Artisan command. Running the
php artisan queue:work
command will
automatically assume that you want to run the worker in
daemon mode. If you would like to process a single job, you
may use the --once
option on the
command:
// デーモンキューワーカの起動
php artisan queue:work
// ジョブを一つ処理する
php artisan queue:work --once
データベースドライバ変更Database Driver Changes
キュー済みのジョブの保存にdatabase
ドライバを使用している場合、jobs_queue_reserved_reserved_at_index
インデックスをドロップし、それからjobs
テーブルのreserved
カラムをドロップしてください。このカラムはdatabase
ドライバを使用時に、必要なくなりました。この変更を完了したら、queue
とreserved_at
カラムの新しい複合インデックスを追加してください。If you are using the
database
driver to store your queued jobs, you
should drop the
jobs_queue_reserved_reserved_at_index
index
then drop the reserved
column from your
jobs
table. This column is no longer required
when using the database
driver. Once you have
completed these changes, you should add a new compound index
on the queue
and reserved_at
columns.
以下は、必要な変更を実行するために使用できる、マイグレーションの例です。Below is an example migration you may use to perform the necessary changes:
public function up()
{
Schema::table('jobs', function (Blueprint $table) {
$table->dropIndex('jobs_queue_reserved_reserved_at_index');
$table->dropColumn('reserved');
$table->index(['queue', 'reserved_at']);
});
Schema::table('failed_jobs', function (Blueprint $table) {
$table->longText('exception')->after('payload');
});
}
public function down()
{
Schema::table('jobs', function (Blueprint $table) {
$table->tinyInteger('reserved')->unsigned();
$table->index(['queue', 'reserved', 'reserved_at']);
$table->dropIndex('jobs_queue_reserved_at_index');
});
Schema::table('failed_jobs', function (Blueprint $table) {
$table->dropColumn('exception');
});
}
イベントデータの変更Event Data Changes
JobProcessing
やJobProcessed
のような多くのジョブは、$data
プロパティを含まなくなりました。同じデータを取得するには、$event->job->payload()
を呼び出すようにアプリケーションを変更してください。Various queue job events such as
JobProcessing
and JobProcessed
no
longer contain the $data
property. You should
update your application to call
$event->job->payload()
to get the
equivalent data.
失敗したジョブのイベントFailed Job Events
AppServiceProvider
の中で、Queue::failing
メソッドを呼び出している場合、メソッド呼び出しを以下のように変更してください。If you are calling the
Queue::failing
method in your
AppServiceProvider
, you should update the
method signature to the following:
use Illuminate\Queue\Events\JobFailed;
Queue::failing(function (JobFailed $event) {
// $event->connectionName
// $event->job
// $event->exception
});
プロセスコントロール拡張Process Control Extension
アプリケーションでキューワーカの--timeout
オプションを使用している場合、pcntl拡張がインストールされているか確認する必要があります。If your application makes use of the
--timeout
option for queue workers, you'll need
to verify that the pcntl
extension[https://secure.php.net/manual/en/pcntl.installation.php]
is installed.
レガシースタイルのキュージョブ上のモデルシリアライズSerializing Models On Legacy Style Queue Jobs
Laravelのジョブは、そのジョブのインスタンスをQueue::push
メソッドに渡すことによりキューされるのが典型的です。しかし、アプリケーションによっては以下のようなレガシー記法で、ジョブをキューしているかもしれません。Typically, jobs in Laravel are queued by
passing a new job instance to the Queue::push
method. However, some applications may be queuing jobs using
the following legacy syntax:
Queue::push('ClassName@method');
この記法を使い、ジョブをキューしていると、Eloquentモデルは自動的にシリアライズされなくなり、キューにより再取得されます。Eloquentモデルをキューで自動的にシリアライズしたい場合は、ジョブクラスでIlluminate\Queue\SerializesModels
トレイトをuseし、新しいpush
記法を使用してジョブをキューしてください。If you are queueing jobs using this
syntax, Eloquent models will no longer be automatically
serialized and re-retrieved by the queue. If you would like
your Eloquent models to be automatically serialized by the
queue, you should use the
Illuminate\Queue\SerializesModels
trait on your
job class and queue the job using the new push
syntax:
Queue::push(new ClassName);
ルーティングRouting
リソースパラメータはデフォルトで単数形にResource Parameters Are Singular By Default
以前のバージョンのLaravelでは、ルートパラメータは単数形ではないRoute::resource
を使い登録していました。これはモデル結合の登録で、予期しない振る舞いを引き起こしました。例として、以下のRoute::resource
呼び出しを見てみましょう。In previous versions of Laravel, route
parameters registered using Route::resource
were not "singularized". This could lead to some
unexpected behavior when registering route model bindings.
For example, given the following
Route::resource
call:
Route::resource('photos', 'PhotoController');
show
へのURIは以下のように定義されるでしょう。The URI for the show
route
would be defined as follows:
/photos/{photos}
Laravel5.3では、全リソースルートのパラメータは、デフォルトで単数形です。そのため、同じRoute::resource
の呼び出しは、以下のようなURIを登録します。In Laravel 5.3, all resource route
parameters are singularized by default. So, the same call to
Route::resource
would register the following
URI:
/photos/{photo}
自動的に単数形のリソースルートパラメータを使うのではなく、以前の振る舞いを続けたい場合は以下のように、AppServiceProvider
の中で、singularResourceParameters
を呼び出してください。If you would like to maintain the
previous behavior instead of automatically singularizing
resource route parameters, you may make the following call
to the singularResourceParameters
method in
your AppServiceProvider
:
use Illuminate\Support\Facades\Route;
Route::singularResourceParameters(false);
リソースルート名はプリフィックスの影響を受けないResource Route Names No Longer Affected By Prefixes
URLプリフィックスはRoute::resource
使用時に、ルートに割り付けるルート名に影響を与えなくなりました。この振る舞いは当初のルート名使用の目的全体を台無しにしてしまいました。URL prefixes no longer affect the route
names assigned to routes when using
Route::resource
, since this behavior defeated
the entire purpose of using route names in the first
place.
もしアプリケーション中に、prefix
オプションを指定したRoute::group
呼び出しの中で、Route::resource
を使用しているならば、全route
ヘルパとUrlGenerator::route
呼び出しでルート名にURIプレフィックスを付けていないことを確認してください。If your application is using
Route::resource
within a
Route::group
call that specified a
prefix
option, you should examine all of your
route
helper and
UrlGenerator::route
calls to verify that you
are no longer appending this URI prefix to the route
name.
この変更により、2つのるーとがおなじ名前を持つようになった場合は、2つの選択肢があります。一つは、name
オプションをRoute::resource
呼び出しで指定し、カスタム名をルートへ指定する方法です。詳細は、リソースルートドキュメントを参照してください。もう一つの方法は、グループにas
オプションを追加する方法です。If this change causes you to have two
routes with the same name, you have two options. First, you
may use the names
option when calling
Route::resource
to specify a custom name for a
given route. Refer to the resource routing
documentation[/docs/5.3/controllers#resource-controllers]
for more information. Alternatively, you may add the
as
option on your route group:
Route::group(['as' => 'admin.', 'prefix' => 'admin'], function () {
//
});
バリデーションValidation
Formリクエスト例外Form Request Exceptions
フォームリクエストのバリデーションに失敗すると、LaravelはHttpException
インスタンスの代わりに、Illuminate\Validation\ValidationException
インスタンスを投げるようになりました。フォームリクエストが投げるHttpException
を自分で補足している場合は、catch
ブロックで、代わりにValidationException
を補足するように変更してください。If a form request's validation fails,
Laravel will now throw an instance of
Illuminate\Validation\ValidationException
instead of an instance of HttpException
. If you
are manually catching the HttpException
instance thrown by a form request, you should update your
catch
blocks to catch the
ValidationException
instead.
Message BagThe Message Bag
Illuminate\Support\MessageBag
インスタンスにメッセージが含まれているかを判定するために、has
メソッドを使用している場合、count
メソッドを代わりに使用してください。has
メソッドは、Message
bagに特定のキーが存在しているかを判定するを判定するのみになり、引数が必要になりました。If you were previously using the
has
method to determine if an
Illuminate\Support\MessageBag
instance
contained any messages, you should use the
count
method instead. The has
method now requires a parameter and only determines if a
specific key exists in the message bag.
NullableプリミティブNullable Primitives
配列、論理型、整数、数値、文字列をバリデートする場合、新しいnullable
ルールを指定していない限り、有効な数値として判断されなくなりました。When validating arrays, booleans,
integers, numerics, and strings, null
will no
longer be considered a valid value unless the rule set
contains the new nullable
rule:
Validate::make($request->all(), [
'field' => 'nullable|max:5',
]);
5.1から5.2.0へのアップグレードUpgrading To 5.2.0 From 5.1
アップデートにかかる時間の見積もり:1時間以下Estimated Upgrade Time: Less Than 1 Hour
Note: {note} We attempt to provide a very comprehensive listing of every possible breaking change made to the framework. However, many of these changes may not apply to your own application.
フレームワークに影響が起きるだろう変更を包括的にリストしました。しかしながら、皆さんのアプリケーションの大半では、変更する必要がないものも多いでしょう。
依存パッケージの更新Updating Dependencies
composer.json
ファイルの内容をlaravel/framework
5.2.*
へ更新してください。Update your
composer.json
file to point to
laravel/framework 5.2.*
.
composer.json
ファイルのrequire-dev
セクションへ、"symfony/dom-crawler":
"~3.0"
と"symfony/css-selector":
"~3.0"
を追加してください。Add
"symfony/dom-crawler":
"~3.0"
and
"symfony/css-selector":
"~3.0"
to the require-dev
section of your composer.json
file.
認証Authentication
設定ファイルConfiguration File
https://github.com/laravel/laravel/blob/5.2/config/auth.phpへ、config/auth.php
設定ファイルを更新してください。You should update your
config/auth.php
configuration file with the
following:
https://github.com/laravel/laravel/blob/5.2/config/auth.php[https://github.com/laravel/laravel/blob/5.2/config/auth.php]
新しいバージョンの内容に更新したら、古い設定ファイルの内容を元に、認証設定オプションを指定してください。Laravel5.1で使用できるEloquentベースの認証サービスが一般的には使われていますが、ほとんどの値はそのまま使用できるでしょう。Once you have updated the file with a fresh copy, set your authentication configuration options to their desired value based on your old configuration file. If you were using the typical, Eloquent based authentication services available in Laravel 5.1, most values should remain the same.
新しいauth.php
設定ファイルのpasswords.users.email
設定オプションへ特に注意を払ってください。デフォルトではLaravel5.2で変更になったらビューへのパスになっていますので、これがアプリケーションの実際のビューパスと一致しているか確認してください。新しい設定ファイルのデフォルト値が実際のビューと一致していない場合は、設定オプションをそれに合わせて変更してください。Take special note of the
passwords.users.email
configuration option in
the new auth.php
configuration file and verify
that the view path matches the actual view path for your
application, as the default path to this view was changed in
Laravel 5.2. If the default value in the new configuration
file does not match your existing view, update the
configuration option.
契約Contracts
Illuminate\Contracts\Auth\Authenticatable
契約を実装しているが、Authenticatable
トレイトを使っていない場合は、新しいgetAuthIdentifierName
メソッドをその契約の実装に追加してください。通常、このメソッドはauthenticatableエンティティの「主キー」のカラム名を返します。たとえば、id
です。If you are implementing the
Illuminate\Contracts\Auth\Authenticatable
contract but are not using the
Authenticatable
trait, you should add a new
getAuthIdentifierName
method to your contract
implementation. Typically, this method will return the
column name of the "primary key" of your
authenticatable entity. For example:
id
.
このインターフェイスを自分で実装していない限り、アプリケーションに影響することはまずないでしょう。This is unlikely to affect your application unless you were manually implementing this interface.
カスタイムドライバCustom Drivers
ユーザを取得するカスタムメソッドを定義するAuth::extend
メソッドを使っている場合、カスタムユーザプロバイダを定義するためのAuth::provider
を使ってください。カスタムプロバイダを定義したら、新しいauth.php
設定ファイルのproviders
配列の中でそれを設定してください。If you are using the
Auth::extend
method to define a custom method
of retrieving users, you should now use
Auth::provider
to define your custom user
provider. Once you have defined the custom provider, you may
configure it in the providers
array of your new
auth.php
configuration file.
カスタム認証プロバイダについての詳細は、認証の完全なドキュメントで調べてください。For more information on custom authentication providers, consult the full authentication documentation[/docs/{{version}}/authentication].
リダイレクトRedirection
Illuminate\Foundation\Auth\AuthenticatesUsers
からloginPath()
メソッドが削除されました。そのため、AuthController
の$loginPath
変数を設定しておく必要が無くなりました。デフォルトで、認証エラーがあった場合、トレイトがデフォルトで以前の場所へ毎回リダイレクトします。The loginPath()
method has
been removed from
Illuminate\Foundation\Auth\AuthenticatesUsers
,
so placing a $loginPath
variable in your
AuthController
is no longer required. By
default, the trait will always redirect users back to their
previous location on authentication errors.
認証Authorization
Illuminate\Auth\Access\UnauthorizedException
はIlluminate\Auth\Access\AuthorizationException
へリネームされました。この例外を自分で補足していない限り、アプリケーションに影響は通常ありません。The
Illuminate\Auth\Access\UnauthorizedException
has been renamed to
Illuminate\Auth\Access\AuthorizationException
.
This is unlikely to affect your application if you are not
manually catching this exception.
コレクションCollections
EloquentベースコレクションEloquent Base Collections
Eloquentコレクションインスタンスのpluck
、keys
、zip
、collapse
、flatten
、flip
メソッドは、ベースコレクション(Illuminate\Support\Collection
)を返すようになりました。The Eloquent collection instance now
returns a base Collection
(Illuminate\Support\Collection
) for the
following methods: pluck
, keys
,
zip
, collapse
,
flatten
, flip
.
キーの保存Key Preservation
slice
、chunk
、reverse
メソッドは、コレクションにキーを残すようになりました。これらのメソッドでキーを保存したくない場合は、Collection
インスタンスのvalues
メソッドを使ってください。The slice
,
chunk
, and reverse
methods now
preserve keys on the collection. If you do not want these
methods to preserve keys, use the values
method
on the Collection
instance.
ComposerクラスComposer Class
Illuminate\Foundation\Composer
クラスはIlluminate\Support\Composer
クラスへ移動しました。このクラスを直接使っていない限り、アプリケーションに通常影響しないでしょう。The
Illuminate\Foundation\Composer
class has been
moved to Illuminate\Support\Composer
. This is
unlikely to affect your application if you were not manually
using this class.
コマンドバスとハンドラCommands And Handlers
自己処理コマンドバスSelf-Handling Commands
ジョブやコマンドのSelfHandling
契約を実装する必要は、もうありません。全ジョブは現在デフォルトで、自己処理型になりました。そのためクラスから、このインターフェイスは取り除いてください。You no longer need to implement the
SelfHandling
contract on your jobs / commands.
All jobs are now self-handling by default, so you can remove
this interface from your classes.
コマンドバスとハンドラの分離Separate Commands & Handlers
Laravel5.2コマンドバスは自己処理コマンドのみのサポートとなったため、コマンドとハンドラーの分離はもうサポートされません。The Laravel 5.2 command bus now only supports self-handling commands and no longer supports separate commands and handlers.
続けてコマンドとハンドラを分けて使いたい場合は、後方コンパチブルをサポートしているLaravel Collectiveパッケージをインストールしてください。(https://github.com/LaravelCollective/bus)If you would like to continue using separate commands and handlers, you may install a Laravel Collective package which provides backwards-compatible support for this: https://github.com/LaravelCollective/bus[https://github.com/laravelcollective/bus]
設定Configuration
環境値Environment Value
app.php
設定ファイルのenv
オプションにデフォルト値が追加され、以下のようになりました。Add an env
configuration
option to your app.php
configuration file that
looks like the following:
'env' => env('APP_ENV', 'production'),
キャッシュとenvCaching And Env
config:cache
コマンドを開発中に使っている場合、設定ファイル中からのみenv
関数を呼び出しており、アプリケーションの他の場所では使用していないことを確実に確かめるべきです。If you are using the
config:cache
command during deployment, you
must make sure that you are only calling
the env
function from within your configuration
files, and not from anywhere else in your
application.
アプリケーション内部でenv
を呼び出しているなら、env
の呼び出しをconfig
へ変換できるように、設定ファイルには実際の設定値を追加し、代わりにその場所からenv
を呼び出す方法を強く推奨します。If you are calling env
from
within your application, it is strongly recommended you add
proper configuration values to your configuration files and
call env
from that location instead, allowing
you to convert your env
calls to
config
calls.
コンパイル済みクラスCompiled Classes
config/compile.php
の中のfiles
配列に、以下の2行があれば削除してください。If present, remove the following lines
from config/compile.php
in the
files
array:
realpath(__DIR__.'/../app/Providers/BusServiceProvider.php'),
realpath(__DIR__.'/../app/Providers/ConfigServiceProvider.php'),
上記のサービスプロバイダーが存在していないと、php artisan
optimize
を実行時にエラーがでます。Not
doing so can trigger an error when running php artisan
optimize
if the service providers listed here do
not exist.
CSRFバリデーションCSRF Verification
CSRFバリデーションはユニットテスト時に自動的に実行されなくなりました。アプリケーションには影響はないでしょう。CSRF verification is no longer automatically performed when running unit tests. This is unlikely to affect your application.
データベースDatabase
MySQLの日付MySQL Dates
MySQL5.7以降では、strict
モードがデフォルトで有効になったため、0000-00-00
00:00:00
が有効な日付として取り扱われなくなりました。全タイムスタンプカラムは、データベースにレコードを挿入する時に、有効なデフォルト値を指定する必要があります。現時点のタイムスタンプをタイムスタンプカラムのデフォルト値にするため、マイグレーションでuseCurrent
メソッドを使うか、null
値を許可するためにnullable
メソッドを指定してください。Starting with MySQL 5.7, 0000-00-00
00:00:00
is no longer considered a valid date,
since strict
mode is enabled by default. All
timestamp columns should receive a valid default value when
you insert records into your database. You may use the
useCurrent
method in your migrations to default
the timestamp columns to the current timestamps, or you may
make the timestamps nullable
to allow
null
values:
$table->timestamp('foo')->nullable();
$table->timestamp('foo')->useCurrent();
$table->nullableTimestamps();
MySQL JSONカラムタイプMySQL JSON Column Type
json
カラムはMySQLドライバにより、実際のJSONカラムが生成されるようになりました。MySQL5.7位上を使用していない場合、このカラムタイプは使用できません。代わりにtext
カラムをマイグレーションで使用してください。The json
column type now
creates actual JSON columns when used by the MySQL driver.
If you are not running MySQL 5.7 or above, this column type
will not be available to you. Instead, use the
text
column type in your migration.
シーディングSeeding
データベースシーディング(初期値設定)を実行時、全Eloquentモデルは保護されなく(unguard)なりました。以前はModel::unguard()
の呼び出しが必要でした。シーディング中にモデルの保護が必要であれば、DatabaseSeeder
クラスのトップでModel::reguard()
を呼び出してください。When running database seeds, all Eloquent
models are now unguarded by default. Previously a call to
Model::unguard()
was required. You can call
Model::reguard()
at the top of your
DatabaseSeeder
class if you would like models
to be guarded during seeding.
EloquentEloquent
日付キャストDate Casts
モデルやモデルのコレクションでtoArray
を呼び出した時に、$casts
プロパティにdate
やdatetime
として追加した属性が、文字列に変換されるようになりました。これにより、日付キャスト変換が$dates
配列で指定された日付と一貫性が取れるようになりました。Any attributes that have been added to
your $casts
property as date
or
datetime
will now be converted to a string when
toArray
is called on the model or collection of
models. This makes the date casting conversion consistent
with dates specified in your $dates
array.
グローバルスコープGlobal Scopes
グローバルスコープの実装が、とても使いやすくなるように実装しなおしました。グローバルスコープにはremove
メソッドは必要なくなりました。そのため、既に書かれたグローバルスコープから削除してください。The global scopes implementation has been
re-written to be much easier to use. Your global scopes no
longer need a remove
method, so it may be
removed from any global scopes you have written.
裏で動作しているクエリビルダインスタンスへアクセスするため、EloquentクエリビルダのgetQuery
を呼び出しているなら、toBase
を呼び出すようにしてください。If you were calling getQuery
on an Eloquent query builder to access the underlying query
builder instance, you should now call
toBase
.
何らかの理由により、remove
メソッドを直接呼び出している場合、代わりに$eloquentBuilder->withoutGlobalScope($scope)
のように呼び出してください。If you were calling the
remove
method directly for any reason, you
should change this call to
$eloquentBuilder->withoutGlobalScope($scope)
.
新しくwithoutGlobalScope
とwithoutGlobalScopes
メソッドをEloquentクエリビルダへ追加しました。$model->removeGlobalScopes($builder)
の呼び出しは、$builder->withoutGlobalScopes()
へ変更してください。New methods
withoutGlobalScope
and
withoutGlobalScopes
have been added to the
Eloquent query builder. Any calls to
$model->removeGlobalScopes($builder)
may be
changed to simply
$builder->withoutGlobalScopes()
.
主キーPrimary keys
デフォルトでEloquentは主キーが整数と仮定しており、整数へ自動的にキャストしています。整数ではない主キーを使用している場合、Eloquentモデルの$incrementing
プロパティをオーバーライドし、false
にしてください。By default, Eloquent assumes your primary
keys are integers and will automatically cast them to
integers. For any primary key that is not an integer you
should override the $incrementing
property on
your Eloquent model to false
:
/**
* IDが自動増分
*
* @var bool
*/
public $incrementing = true;
イベントEvents
コアイベントオブジェクトCore Event Objects
Laravelが発行するコアイベントのいくつかが、文字列と動的パラメータの代わりに、イベントオブジェクトを使うようになりました。以下のリストは、旧イベント名とオブジェクトベースの対応するイベントクラスです。Some of the core events fired by Laravel now use event objects instead of string event names and dynamic parameters. Below is a list of the old event names and their new object based counterparts:
旧イベント名Old | 新イベントクラスNew |
---|---|
artisan.start artisan.start |
Illuminate\Console\Events\ArtisanStarting Illuminate\Console\Events\ArtisanStarting |
auth.attempting auth.attempting |
Illuminate\Auth\Events\Attempting Illuminate\Auth\Events\Attempting |
auth.login auth.login |
Illuminate\Auth\Events\Login Illuminate\Auth\Events\Login |
auth.logout auth.logout |
Illuminate\Auth\Events\Logout Illuminate\Auth\Events\Logout |
cache.missed cache.missed |
Illuminate\Cache\Events\CacheMissed Illuminate\Cache\Events\CacheMissed |
cache.hit cache.hit |
Illuminate\Cache\Events\CacheHit Illuminate\Cache\Events\CacheHit |
cache.write cache.write |
Illuminate\Cache\Events\KeyWritten Illuminate\Cache\Events\KeyWritten |
cache.delete cache.delete |
Illuminate\Cache\Events\KeyForgotten Illuminate\Cache\Events\KeyForgotten |
connection.{name}.beginTransaction connection.{name}.beginTransaction |
Illuminate\Database\Events\TransactionBeginning Illuminate\Database\Events\TransactionBeginning |
connection.{name}.committed connection.{name}.committed |
Illuminate\Database\Events\TransactionCommitted Illuminate\Database\Events\TransactionCommitted |
connection.{name}.rollingBack connection.{name}.rollingBack |
Illuminate\Database\Events\TransactionRolledBack Illuminate\Database\Events\TransactionRolledBack |
illuminate.query illuminate.query |
Illuminate\Database\Events\QueryExecuted Illuminate\Database\Events\QueryExecuted |
illuminate.queue.before illuminate.queue.before |
Illuminate\Queue\Events\JobProcessing Illuminate\Queue\Events\JobProcessing |
illuminate.queue.after illuminate.queue.after |
Illuminate\Queue\Events\JobProcessed Illuminate\Queue\Events\JobProcessed |
illuminate.queue.failed illuminate.queue.failed |
Illuminate\Queue\Events\JobFailed Illuminate\Queue\Events\JobFailed |
illuminate.queue.stopping illuminate.queue.stopping |
Illuminate\Queue\Events\WorkerStopping Illuminate\Queue\Events\WorkerStopping |
mailer.sending mailer.sending |
Illuminate\Mail\Events\MessageSending Illuminate\Mail\Events\MessageSending |
router.matched router.matched |
Illuminate\Routing\Events\RouteMatched Illuminate\Routing\Events\RouteMatched |
各イベントオブジェクトはLaravel5.1のイベントハンドラへ渡されていたものと、完全に同じパラメータを含んでいます。たとえば、5.1.*のDB::listen
を使用していたなら、5.2では次のように更新します。Each of these event objects contains
exactly the same parameters that were
passed to the event handler in Laravel 5.1. For example, if
you were using DB::listen
in 5.1., you may
update your code like so for 5.2.:
DB::listen(function ($event) {
dump($event->sql);
dump($event->bindings);
});
新しいオブジェクトクラスを調べ、publicプロパティを確認してください。You may check out each of the new event object classes to see their public properties.
例外ハンドラException Handling
App\Exceptions\Handler
クラスの$dontReport
プロパティは以下の例外タイプの最低1つを含むように更新してください。Your App\Exceptions\Handler
class' $dontReport
property should be updated
to include at least the following exception
types:
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* レポートしたくない例外のリスト
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
ヘルパ関数Helper Functions
url()
ヘルパ関数が、引数のパスの指定がない場合にIlluminate\Routing\UrlGenerator
を返すようになりました。The url()
helper function
now returns a Illuminate\Routing\UrlGenerator
instance when no path is provided.
暗黙のモデル結合Implicit Model Binding
Laravel5.2は「暗黙のモデル結合」を導入しました。URIに現れる識別子を元にルートとコントローラへモデルインスタンスを自動的に依存注入する新しい機能です。しかし、これによりモデルインスタンスをタイプヒントしたルートとコントローラの振る舞いがかわりました。Laravel 5.2 includes "implicit model binding", a convenient new feature to automatically inject model instances into routes and controllers based on the identifier present in the URI. However, this does change the behavior of routes and controllers that type-hint model instances.
ルートやコントローラでモデルインスタンスをタイプヒントし、空のモデルインスタンスが注入されることを期待している場合、タイプヒントを削除し、ルートかコントローラ内で直接空のモデルを生成してください。そうしなければ、LaravelはルートURIにあるIDを元にデータベースから既存のモデルインスタンスを取得しようとします。If you were type-hinting a model instance in your route or controller and were expecting an empty model instance to be injected, you should remove this type-hint and create an empty model instance directly within your route or controller; otherwise, Laravel will attempt to retrieve an existing model instance from the database based on the identifier present in the route's URI.
IronMQIronMQ
IronMQキュードライバーはそれ自身のパッケージから削除されたため、コアフレームワークには含まれなくなりました。The IronMQ queue driver has been moved into its own package and is no longer shipped with the core framework.
https://github.com/LaravelCollective/iron-queue
ジョブ/キューJobs / Queue
php artisan
make:job
コマンドは、デフォルトで「キュー投入(queued)」ジョブクラスを定義するようになりました。「同期(sync)」ジョブを生成したい場合は、コマンド実行時に--sync
オプションを付けてください。The php artisan make:job
command now creates a "queued" job class
definition by default. If you would like to create a
"sync" job, use the --sync
option
when issuing the command.
メールMail
pretend
メール設定オプションは削除されました。代わりにlog
メールドライバを使ってください。pretend
と同じ機能で、メールメッセージについてより情報がログされます。The pretend
mail
configuration option has been removed. Instead, use the
log
mail driver, which performs the same
function as pretend
and logs even more
information about the mail message.
ペジネーションPagination
フレームワークが生成する他のURLとの一貫性を保つため、ペジネーションURLは最後のスラッシュを含まないようになりました。これがアプリケーションに影響を与えることはないでしょう。To be consistent with other URLs generated by the framework, the paginator URLs no longer contain a trailing slash. This is unlikely to affect your application.
サービスプロバイダService Providers
app.php
設定ファイルのサービスプロバイダリストから、Illuminate\Foundation\Providers\ArtisanServiceProvider
を削除してください。The
Illuminate\Foundation\Providers\ArtisanServiceProvider
should be removed from your service provider list in your
app.php
configuration file.
app.php
設定ファイルのサービスプロバイダリストから、Illuminate\Routing\ControllerServiceProvider
を削除してください。The
Illuminate\Routing\ControllerServiceProvider
should be removed from your service provider list in your
app.php
configuration file.
セッションSessions
認証システムの変更により、Laravel5.2へアップグレードした時点で、既存のセッションは無効になります。Because of changes to the authentication system, any existing sessions will be invalidated when you upgrade to Laravel 5.2.
データベース Session DriverDatabase Session Driver
ユーザID、IPアドレス、ユーザエージェントのような情報をより含む、新しいdatabase
セッションドライバが書かれました。古いドライバーを使い続けたい場合は、session.php
設定ファイルへlegacy-database
ドライバを指定してください。A new database
session
driver has been written for the framework which includes
more information about the user such as their user ID, IP
address, and user-agent. If you would like to continue using
the old driver you may specify the
legacy-database
driver in your
session.php
configuration file.
新しいドライバーを使用する場合、セッションのデータベーステーブルへ、user_id
(NULL値を許す整数)
、ip_address
(NULL値を許す整数)
、user_agent
(テキスト)
カラムを追加してください。If you
would like to use the new driver, you should add the
user_id (nullable integer)
, ip_address
(nullable string)
, and user_agent
(text)
columns to your session database
table.
StringyStringy
"Stringy"ライブラリはフレームワーク含まれなくなりました。アプリケーションで使用したい場合は、Composerを使いインストールしてください。The "Stringy" library is no longer included with the framework. You may install it manually via Composer if you wish to use it in your application.
バリデーションValidation
例外タイプException Types
ValidatesRequests
トレイトはIlluminate\Http\Exception\HttpResponseException
インスタンスの代わりに、Illuminate\Foundation\Validation\ValidationException
インスタンスを投げるようになりました。自分でこの例外を補足していなければ、アプリケーションに影響はないでしょう。The ValidatesRequests
trait
now throws an instance of
Illuminate\Foundation\Validation\ValidationException
instead of throwing an instance of
Illuminate\Http\Exception\HttpResponseException
.
This is unlikely to affect your application unless you were
manually catching this exception.
非推奨Deprecations
以下の機能は5.2で非推奨になり、2016年6月の5.3のリリースで削除されます。The following features are deprecated in 5.2 and will be removed in the 5.3 release in June 2016:
Illuminate\Contracts\Bus\SelfHandling
契約。ジョブから削除してください。Illuminate\Contracts\Bus\SelfHandling
contract. Can be removed from jobs.- コレクション、クエリビルダ、Eloquentクエリビルダオブジェクトの
lists
メソッドはpluck
ヘリネームされました。メソッドの使い方は同じです。Thelists
method on the Collection, query builder and Eloquent query builder objects has been renamed topluck
. The method signature remains the same. Route::controller
を使う暗黙のコントローラルート定義は非推奨になりました。ルートファイルで明確に定義してください。これはパッケージから削除されます。Implicit controller routes usingRoute::controller
have been deprecated. Please use explicit route registration in your routes file. This will likely be extracted into a package.get
、post
やその他のルート定義ヘルパ関数は削除されます。代わりにRoute
ファサードを使ってください。Theget
,post
, and other route helper functions have been removed. You may use theRoute
facade instead.- 5.1の
database
セッションドライバーはlegacy-database
ヘリネームされ、削除予定です。前述の「データベースセッションドライバ」をお読みください。Thedatabase
session driver from 5.1 has been renamed tolegacy-database
and will be removed. Consult notes on the "database session driver" above for more information. - PHPが持っている
random_bytes
関数がより好ましいため、Str::randomBytes
関数は非推奨になりました。TheStr::randomBytes
function has been deprecated in favor of therandom_bytes
native PHP function. - PHPが持っている
hash_equals
関数がより好ましいため、Str::equals
関数は非推奨になりました。TheStr::equals
function has been deprecated in favor of thehash_equals
native PHP function. Illuminate\Support\HtmlString
がより好ましいため、Illuminate\View\Expression
は非推奨になりました。Illuminate\View\Expression
has been deprecated in favor ofIlluminate\Support\HtmlString
.WincacheStore
キャッシュドライバーは削除されました。TheWincacheStore
cache driver has been removed.
5.1.11へのアップグレードUpgrading To 5.1.11
Laravel5.1.11は認可とポリシーをサポートします。既存のLaravel5.1アプリケーションへこれらの新しい機能を組み込むのも簡単です。Laravel 5.1.11 includes support for authorization[/docs/{{version}}/authorization] and policies[/docs/{{version}}/authorization#policies]. Incorporating these new features into your existing Laravel 5.1 applications is simple.
Note: {note} These upgrades are optional, and ignoring them will not affect your application.
これらのアップグレードは任意です。行わなくてもアプリケーションの実行に影響は与えません。
ポリシーディレクトリの作成Create The Policies Directory
まずアプリケーションへ空のapp/Policies
ディレクトリを作成してください。First,
create an empty
app/Policies
directory within your
application.
AuthServiceProviderとGateファサードの作成と登録Create / Register The AuthServiceProvider & Gate Facade
app/Providers
ディレクトリにAuthServiceProvider
を作成します。
GitHubからデフォルトプロバイダの内容をコピーしてください。もしアプリケーションでカスタム名前空間を使用している場合はプロバイダの名前空間を変更してください。プロバイダを作成したら、app.php
設定ファイルのproviders
配列へ確実に登録してください。Create
a
AuthServiceProvider
within your
app/Providers
directory. You may copy
the contents of the
default provider from
GitHub[https://raw.githubusercontent.com/laravel/laravel/5.1/app/Providers/AuthServiceProvider.php].
Remember to change the
provider's namespace if
your application is
using a custom
namespace. After
creating the provider,
be sure to register it
in your
app.php
configuration file's
providers
array.
さらに、Gate
ファサードをapp.php
ファイルのaliases
配列へ登録する必要もあります。Also,
you should register the
Gate
facade
in your
app.php
configuration file's
aliases
array:
'Gate' => Illuminate\Support\Facades\Gate::class,
Userモデルの更新Update The User Model
手順の2つ目は、App\User
モデルへIlluminate\Foundation\Auth\Access\Authorizable
トレイトのuseと、Illuminate\Contracts\Auth\Access\Authorizable
契約を追加します。Secondly,
use the
Illuminate\Foundation\Auth\Access\Authorizable
trait and
Illuminate\Contracts\Auth\Access\Authorizable
contract on your
App\User
model:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
ベースコントローラーの更新Update The Base Controller
続いて、App\Http\Controllers\Controller
ベースコントローラーでIlluminate\Foundation\Auth\Access\AuthorizesRequests
トレイトをuseするように更新します。Next,
update your base
App\Http\Controllers\Controller
controller to use the
Illuminate\Foundation\Auth\Access\AuthorizesRequests
trait:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
5.1.0へのアップグレードUpgrading To 5.1.0
アップデートにかかる時間の見積もり:1時間以下Estimated Upgrade Time: Less Than 1 Hour
bootstrap/autoload.php
の更新Update
bootstrap/autoload.php
bootstrap/autoload.php
の中の$compiledPath
変数を次のように変更してください。Update
the
$compiledPath
variable in
bootstrap/autoload.php
to the
following:
$compiledPath = __DIR__.'/cache/compiled.php';
bootstrap/cache
ディレクトリ作成Create
bootstrap/cache
Directory
bootstrap
ディレクトリの中に、cache
ディレクトリ(bootstrap/cache
)を作成してください。.gitignore
ファイルをこのディレクトリに以下の内容で作成してください。Within
your
bootstrap
directory, create a
cache
directory
(bootstrap/cache
).
Place a
.gitignore
file in this directory
with the following
contents:
*
!.gitignore
compiled.php
、routes.php
、config.php
、services.json
など一時的な最適化のためのファイルをフレームワークが保存するために使用します。This
directory should be
writable, and will be
used by the framework to
store temporary
optimization files like
compiled.php
,
routes.php
,
config.php
,
and
services.json
.
BroadcastServiceProvider
プロバイダ追加Add
BroadcastServiceProvider
Provider
config/app.php
設定ファイルのproviders
配列にIlluminate\Broadcasting\BroadcastServiceProvider
を追加します。Within
your
config/app.php
configuration file, add
Illuminate\Broadcasting\BroadcastServiceProvider
to the
providers
array.
認証Authentication
AuthenticatesAndRegistersUsers
トレイトを使用しているAuthController
を使用している場合は、新しいユーザのバリデーションと生成方法に多少変更が必要です。If
you are using the
provided
AuthController
which uses the
AuthenticatesAndRegistersUsers
trait, you will need to
make a few changes to
how new users are
validated and
created.
最初に、Guard
とRegistrar
をベースのコンストラクターに渡す必要は無くなりました。コントローラーのコンストラクターから、これらの依存指定を削除できます。First,
you no longer need to
pass the
Guard
and
Registrar
instances to the base
constructor. You can
remove these
dependencies entirely
from your controller's
constructor.
次に、Laravel5.0で使用していたApp/Services/Registrar
クラスは必要ありません。このクラスからvalidator
とcreate
メソッドをそのままAuthController
にコピー&ペーストしてください。これ以上の変更は必要ありませんが、AuthController
の最初でValidator
ファサードとUser
モデルをインポートする必要はあるでしょう。Secondly,
the
App\Services\Registrar
class used in Laravel
5.0 is no longer needed.
You can simply copy and
paste your
validator
and create
method from this class
directly into your
AuthController
.
No other changes should
need to be made to these
methods; however, you
should be sure to import
the
Validator
facade and your
User
model
at the top of your
AuthController
.
PasswordコントローラーPassword Controller
Laravelに含まれているPasswordController
は、依存をコンストラクターで要求する必要が無くなりました。5.0以下で必要であった依存は両方共取り除いてください。The
included
PasswordController
no longer requires any
dependencies in its
constructor. You may
remove both of the
dependencies that were
required under
5.0.
バリデーションValidation
もしベースコントローラクラスのformatValidationErrors
メソッドをオーバーライドしているなら、Illuminate\Validation\Validator
具象クラスの代わりにIlluminate\Contracts\Validation\Validator
契約をタイプヒントで指定する必要があります。If
you are overriding the
formatValidationErrors
method on your base
controller class, you
should now type-hint the
Illuminate\Contracts\Validation\Validator
contract instead of the
concrete
Illuminate\Validation\Validator
instance.
同様に、ベースコントローラークラスのformatErrors
メソッドをオーバーライドしているなら、Illuminate\Validation\Validator
具象クラスの代わりにIlluminate\Contracts\Validation\Validator
契約をタイプヒントで指定する必要があります。Likewise,
if you are overriding
the
formatErrors
method on the base form
request class, you
should now type-hint
Illuminate\Contracts\Validation\Validator
contract instead of the
concrete
Illuminate\Validation\Validator
instance.
マイグレーションMigrations
SQLiteデータベースのカラム名を変更したり、カラムをドロップするマイグレーションが存在する場合、composer.json
ファイルにdoctrine/dbal
依存パッケージを追加し、このライブラリをインストールするために、端末でcomposer
update
コマンドを実行する必要があります。If
you have any migrations
that rename a column or
any migrations that drop
columns from a SQLite
database, you will need
to add the
doctrine/dbal
dependency to your
composer.json
file and run the
composer
update
command in your terminal
to install the
library.
EloquentEloquent
create
メソッドThe
create
Method
Eloquentのcreate
メソッドが引数無しで呼び出せるようになりました。もしモデルのcreate
メソッドをオーバーライドしている場合は、$attributes
引数にデフォルト値として配列を指定してください。Eloquent's
create
method can now be called
without any parameters.
If you are overriding
the create
method in your own
models, set the default
value of the
$attributes
parameter to an
array:
public static function create(array $attributes = [])
{
// カスタム実装…
}
find
メソッドThe
find
Method
モデルでfind
メソッドをオーバーライドし、そのカスタムメソッド中でparent::find()
を呼んでいるなら、Eloquentクエリビルダのfind
メソッドを呼び出すように変更してください。If
you are overriding the
find
method
in your own models and
calling
parent::find()
within your custom
method, you should now
change it to call the
find
method
on the Eloquent query
builder:
public static function find($id, $columns = ['*'])
{
$model = static::query()->find($id, $columns);
// ...
return $model;
}
lists
メソッドThe
lists
Method
Eloquentのクエリ―のlists
メソッドは通常の配列の代わりに「コレクション」インスタンスを返すようになりました。コレクションを通常の配列に変換したい場合は、all
メソッドを使用してください。The
lists
method now returns a
Collection
instance instead of a
plain array for Eloquent
queries. If you would
like to convert the
Collection
into a plain array, use
the all
method:
User::lists('id')->all();
クエリビルダのlists
はそのまま配列を返すことに注意してください。Be
aware that the Query
Builder
lists
method still returns an
array.
日付のフォーマットDate Formatting
これまでは保存されるEloquentの日付フィールドのフォーマットは、モデルのgetDateFormat
メソッドをオーバーライドすることで変更できました。これはまだ有効ですが、メソッドをオーバーライドする代わりに、モデルインスタンスの$dateFormat
プロパティーを指定するほうが簡単で便利でしょう。Previously,
the storage format for
Eloquent date fields
could be modified by
overriding the
getDateFormat
method on your model.
This is still possible;
however, for convenience
you may simply specify a
$dateFormat
property on the model
instead of overriding
the method.
日付フォーマットはモデルを配列やJSONにシリアライズするときにも適用されるようになりました。Laravelを5.0から5.1へアップグレードすると、JSONシリアライズされたデータフィールドのフォーマットは変わってしまいます。シリアライズされるモデルへ日付フォーマットを指定するには、モデルのserializeDate(DateTime
$date)
メソッドをオーバーライドしてください。このメソッドにより、保存されるフォーマットを変更せずに、シリアライズされるEloquentの日付フィールドのフォーマットを柔軟にコントロールできます。The
date format is also now
applied when serializing
a model to an
array
or
JSON. This may change
the format of your JSON
serialized date fields
when migrating from
Laravel 5.0 to 5.1. To
set a specific date
format for serialized
models, you may override
the
serializeDate(DateTime
$date)
method
on your model. This
method allows you to
have granular control
over the formatting of
serialized Eloquent date
fields without changing
their storage
format.
コレクションクラスThe Collection Class
sort
メソッドThe
sort
Method
sort
メソッドは既存のコレクションを変更する代わりに、新しいコレクションインスタンスを返すようになりました。The
sort
method
now returns a fresh
collection instance
instead of modifying the
existing
collection:
$collection = $collection->sort($callback);
sortBy
メソッドThe
sortBy
Method
sortBy
メソッドは既存のコレクションを更新する代わりに、新しいコレクションインスタンスを返すようになりました。The
sortBy
method now returns a
fresh collection
instance instead of
modifying the existing
collection:
$collection = $collection->sortBy('name');
groupBy
メソッドThe
groupBy
Method
groupBe
メソッドは親のCollection
の中の各アイテムごとにCollection
を返すようになりました。全アイテムをプレーンな配列に戻したい場合は、map
を適用してください。The
groupBy
method now returns
Collection
instances for each item
in the parent
Collection
.
If you would like to
convert all of the items
back to plain arrays,
you may map
over them:
$collection->groupBy('type')->map(function ($item)
{
return $item->all();
});
lists
メソッドThe
lists
Method
lists
メソッドは通常の配列の代わりに「コレクション」インスタンスを返すようになりました。コレクションを通常の配列に変換したい場合は、all
メソッドを使用してください。The
lists
method now returns a
Collection
instance instead of a
plain array. If you
would like to convert
the
Collection
into a plain array, use
the all
method:
$collection->lists('id')->all();
コマンドとハンドラCommands & Handlers
app/Commands
ディレクトリはapp/Jobs
へ名前が変更されました。しかし、コマンドを全部新しい場所へ移動する必要はありませんし、make:command
とhandler:command
Artisanコマンドも続けて使用できます。The
app/Commands
directory has been
renamed to
app/Jobs
.
However, you are not
required to move all of
your commands to the new
location, and you may
continue using the
make:command
and
handler:command
Artisan commands to
generate your
classes.
同様に、app/Handlers
ディレクトリはapp/Listeners
に名前が変更され、イベントリスナだけが含まれるようになりました。しかし、既に存在するコマンドとイベントハンドラを移動したり、名前を変えたりする必要はありません。handler:event
コマンドもイベントハンドラを生成するために続けて使用できます。Likewise,
the
app/Handlers
directory has been
renamed to
app/Listeners
and now only contains
event listeners.
However, you are not
required to move or
rename your existing
command and event
handlers, and you may
continue to use the
handler:event
command to generate
event
handlers.
Laravel5.0フォルダー構造との後方互換性を提供しているので、アプリケーションをLaravel5.1へアップグレードし、都合の良い時にイベントとコマンドを新しい場所へゆっくりアップグレードしてください。By providing backwards compatibility for the Laravel 5.0 folder structure, you may upgrade your applications to Laravel 5.1 and slowly upgrade your events and commands to their new locations when it is convenient for you or your team.
BladeBlade
BladeコンパイラーからcreateMatcher
、createOpenMatcher
、createPlainMatcher
メソッドが削除されました。Laravel5.1のBladeでは新しいdirective
メソッドでカスタムディレクティブを作成してください。Bladeの拡張のドキュメントで詳細を確認してください。The
createMatcher
,
createOpenMatcher
,
and
createPlainMatcher
methods have been
removed from the Blade
compiler. Use the new
directive
method to create custom
directives for Blade in
Laravel 5.1. Consult the
extending
blade[/docs/{{version}}/blade#extending-blade]
documentation for more
information.
テストTests
tests/TestCase.php
ファイルにprotectedの$baseUrl
プロパティーを追加してください。Add
the protected
$baseUrl
property to the
tests/TestCase.php
file:
protected $baseUrl = 'http://localhost';
言語ファイルTranslation Files
ベンダーパッケージの公開言語ファイルのデフォルトディレクトリが変更になりました。ベンダーパッケージ言語ファイルはresources/lang/パッケージ/{ローカル}/{名前空間}
からresources/lang/ベンダー/{名前空間}/{ローカル}
へ移動してください。たとえばAcme/Anvil
パッケージのacme/anvil::foo
名前空間、英語の言語ファイルはresources/lang/packages/en/acme/anvil/foo.php
からresources/lang/vendor/acme/anvil/en/foo.php
へ移動します。The
default directory for
published language files
for vendor packages has
been moved. Move any
vendor package language
files from
resources/lang/packages/{locale}/{namespace}
to
resources/lang/vendor/{namespace}/{locale}
directory. For example,
Acme/Anvil
package's
acme/anvil::foo
namespaced English
language file would be
moved from
resources/lang/packages/en/acme/anvil/foo.php
to
resources/lang/vendor/acme/anvil/en/foo.php
.
Amazon WebサービスSDKAmazon Web Services SDK
AWS SQSキュードライバかAWS SES メールドライバを使っている場合は、インストール済みのAWS PHP SDKをバージョン3.0へアップデートする必要があります。If you are using the AWS SQS queue driver or the AWS SES e-mail driver, you should update your installed AWS PHP SDK to version 3.0.
Amazon S3ファイルシステムドライバを使用している場合は、Composerにより対応するファイルシステムパッケージを更新する必要があります。If you are using the Amazon S3 filesystem driver, you will need to update the corresponding Flysystem package via Composer:
- Amazon S3:
league/flysystem-aws-s3-v3 ~1.0
Amazon S3:league/flysystem-aws-s3-v3 ~1.0
非推奨Deprecations
以下のLaravelの機能は非推奨になり、2015年12月にリリースされるLaravel 5.2で完全に削除されます。The following Laravel features have been deprecated and will be removed entirely with the release of Laravel 5.2 in December 2015:
5.0.16へのアップグレードUpgrading To 5.0.16
bootstrap/autoload.php
ファイル中の$compiledPath
変数を変更してください。In
your
bootstrap/autoload.php
file, update the
$compiledPath
variable
to:
$compiledPath = __DIR__.'/../vendor/compiled.php';
サービスプロバイダService Providers
app.php
設定ファイルのサービスプロバイダリストから、App\Providers\BusServiceProvider
を削除してください。The
App\Providers\BusServiceProvider
may be removed from
your service
provider list in
your
app.php
configuration
file.
app.php
設定ファイルのサービスプロバイダリストから、App\Providers\ConfigServiceProvider
を削除してください。The
App\Providers\ConfigServiceProvider
may be removed from
your service
provider list in
your
app.php
configuration
file.
4.2から5.0へのアップグレードUpgrading To 5.0 From 4.2
新しくインストール、その後で移行Fresh Install, Then Migrate
推奨するアップグレード方法は、新しくLaravel5.0
をインストールし、それから4.2
サイト独自のファイルを新しくインストールした環境へコピーすることです。コピーするファイルにはコントローラー、ルート、Eloquentモデル、Artisanコマンド、アセット、その他あなたのアプリケーション限定のコードを含みます。The
recommended method
of upgrading is to
create a new Laravel
5.0
install and then to
copy your
4.2
site's unique
application files
into the new
application. This
would include
controllers, routes,
Eloquent models,
Artisan commands,
assets, and other
code specific files
to your
application.
まずローカル環境の新しいディレクトリへLaravel5.0アプリケーションをインストールしてください。5.0よりも新しいバージョンはインストールしないでください。最初に5.0へのマイグレーションを完了させる必要があります。各手順の詳細は、以降で紹介します。To start, install a new Laravel 5.0 application[/docs/5.0/installation] into a fresh directory in your local environment. Do not install any versions newer than 5.0 yet, since we need to complete the migration steps for 5.0 first. We'll discuss each piece of the migration process in further detail below.
Composerの依存とパッケージComposer Dependencies & Packages
追加しているComposerの依存パッケージを5.0アプリケーションへコピーするのを忘れないでください。SDKのような、サードパーティのコードも忘れずに。Don't forget to copy any additional Composer dependencies into your 5.0 application. This includes third-party code such as SDKs.
リリース後しばらく、Laravel限定のパッケージはLaravel5と互換性がないかも知れません。Laravel5向きの対応バージョンが用意されるか、メンテナーに確認しましょう。Composerの依存パッケージをアプリケーションに追加したら、composer
updata
を実行する必要があります。Some
Laravel-specific
packages may not be
compatible with
Laravel 5 on initial
release. Check with
your package's
maintainer to
determine the proper
version of the
package for Laravel
5. Once you have
added any additional
Composer
dependencies your
application needs,
run composer
update
.
名前空間Namespacing
Laravel4のデフォルトでは、アプリケーションのコードに名前空間は使用されていません。そのため、例えば、全Eloquentモデルとコントローラーは、ただ「グローバル」な名前空間下に置かれています。手早く移行するには、Laravel5でも同様にグローバル名前空間下へ、それらのクラスを設置しましょう。By default, Laravel 4 applications did not utilize namespacing within your application code. So, for example, all Eloquent models and controllers simply lived in the "global" namespace. For a quicker migration, you can simply leave these classes in the global namespace in Laravel 5 as well.
設定Configuration
環境変数の移行Migrating Environment Variables
新しい.env.example
ファイルを.env
へコピーします。古いバージョンの.env.php
ファイルに該当します。APP_ENV
やAPP_KEY
(暗号化キー)、データベース接続情報、キャッシュやセッションのドライバのような値を適切に設置してください。Copy
the new
.env.example
file to
.env
,
which is the
5.0
equivalent of the
old
.env.php
file. Set any
appropriate values
there, like your
APP_ENV
and
APP_KEY
(your encryption
key), your database
credentials, and
your cache and
session
drivers.
さらに、古い.env.php
ファイル中で変更した値を.env
(ローカル環境で本当に使用される値)と.env.example
(他のチームメンバーに参考にしてもらう値)にコピーします。Additionally,
copy any custom
values you had in
your old
.env.php
file and place them
in both
.env
(the real value for
your local
environment) and
.env.example
(a sample
instructional value
for other team
members).
環境設定の詳細は、ドキュメントを読んでください。For more information on environment configuration, view the full documentation[/docs/{{version}}/installation#environment-configuration].
Note:
Laravel5アプリケーションを本番サーバーへデプロイする前に、適切な値を設置した.env
ファイルを用意しておく必要があります。{note} You will need to place the appropriate.env
file and values on your production server before deploying your Laravel 5 application.
設定ファイルConfiguration Files
Laravel5.0では、特定の環境のために設定ファイルを指定する、app/config/{環境名}/
ディレクトリ構造はもう使われません。代わりに、各環境に用意する.env
へ設定値を移動します。それから、設定ファイル中でenv('キー',
'デフォルト値')
を使用して、値にアクセスします。config/database.php
設定ファイルに設定例があります。Laravel
5.0 no longer uses
app/config/{environmentName}/
directories to
provide specific
configuration files
for a given
environment.
Instead, move any
configuration values
that vary by
environment into
.env
,
and then access them
in your
configuration files
using
env('key',
'default value')
.
You will see
examples of this in
the
config/database.php
configuration
file.
config
ディレクトリ下の設定ファイルには、全環境に渡り変更しない値を直接設置するか、環境ごとに変化する値をロードするためenv()
を使うか、どちらかで設定値を指定します。Set
the config files in
the
config/
directory to
represent either the
values that are
consistent across
all of your
environments, or set
them to use
env()
to load values that
vary by
environment.
.env
ファイルにキーを追加したら、同様に参考値を.env.example
ファイルへ追加するのを忘れないでください。これにより、あなたのチームメンバーが自分の.env
ファイルを作成しやすくなります。Remember,
if you add more keys
to .env
file, add sample
values to the
.env.example
file as well. This
will help your other
team members create
their own
.env
files.
ルートRoutes
古いroutes.php
を新しいapp/Http/routes.php
へ、コピー&貼付けしてください。Copy
and paste your old
routes.php
file into your new
app/Http/routes.php
.
コントローラーControllers
次に、全コントローラーをapp/Http/Controllers
ディレクトリへ移動します。このガイドでは名前空間を利用した以降を行わないため、composer.json
ファイルのclassmap
ディレクティブへ、app/Http/Controllers
を追加してください。次に、app/Http/Controllers/Controller.php
抽象ベースクラスから、名前空間を削除します。移行するコントローラーはこのベースクラスを拡張していることを確認してください。Next,
move all of your
controllers into the
app/Http/Controllers
directory. Since we
are not going to
migrate to full
namespacing in this
guide, add the
app/Http/Controllers
directory to the
classmap
directive of your
composer.json
file. Next, you can
remove the namespace
from the abstract
app/Http/Controllers/Controller.php
base class. Verify
that your migrated
controllers are
extending this base
class.
app/Providers/RouteServiceProvider.php
ファイルの中で、namespace
プロパティをnull
に設定してください。In
your
app/Providers/RouteServiceProvider.php
file, set the
namespace
property to
null
.
ルートフィルターRoute Filters
フィルターの定義をapp/filters.php
から、app/Providers/RouteServiceProvider.php
のboot()
メソッドの中へコピーします。app/Providers/RouteServiceProvider.php
にuse
Illuminate\Support\Facades\Route;
の1行を追加し、Route
ファサードを使い続けられるようにします。Copy
your filter bindings
from
app/filters.php
and place them into
the
boot()
method of
app/Providers/RouteServiceProvider.php
.
Add use
Illuminate\Support\Facades\Route;
in the
app/Providers/RouteServiceProvider.php
in order to continue
using the
Route
Facade.
auth
とcsrf
のような、Laravel4デフォルトフィルターは移動しないでください。ミドルウェアとしてLaravel5に用意されています。ルートやコントローラーで、古いデフォルトフィルターの使用箇所(例えば、['before'
=>
'auth']
)を新しいミドルウェアを使用するように書き換えてください。(例えば、['middleware'
=>
'auth']
)You
do not need to move
over any of the
default Laravel 4.0
filters such as
auth
and
csrf
;
they're all here,
but as middleware.
Edit any routes or
controllers that
reference the old
default filters
(e.g.
['before'
=>
'auth']
)
and change them to
reference the new
middleware (e.g.
['middleware'
=>
'auth'].
)
フィルターはLaravel5でも廃止されていません。カスタムフィルターを定義して、before
とafter
を使用し指定できます。Filters
are not removed in
Laravel 5. You can
still bind and use
your own custom
filters using
before
and
after
.
グローバルCSRFGlobal CSRF
デフォルトで、CSRF保護が、全ルートで有効になりました。これを無効にするか、特定のルートだけに手動で有効にしたいのでしたら、以下の行をApp\Http\Kernel
ファイル中のmiddleware
配列から削除してください。By
default, CSRF
protection[/docs/{{version}}/routing#csrf-protection]
is enabled on all
routes. If you'd
like to disable
this, or only
manually enable it
on certain routes,
remove this line
from
App\Http\Kernel
's
middleware
array:
'App\Http\Middleware\VerifyCsrfToken',
続いて、次の1行を$routeMiddleware
に追加します。If
you want to use it
elsewhere, add this
line to
$routeMiddleware
:
'csrf' => 'App\Http\Middleware\VerifyCsrfToken',
これで、個別のルート/コントローラーに対し、['middleware'
=>
'csrf']
を指定することで、ミドルウェアを追加できるようになります。ミドルウェアの詳細は、ドキュメントを参照してください。Now
you can add the
middleware to
individual routes /
controllers using
['middleware'
=>
'csrf']
on the route. For
more information on
middleware, consult
the full
documentation[/docs/{{version}}/middleware].
EloquentモデルEloquent Models
Eloquentモデルを設置するために、app/Models
ディレクトリを作成することもできます。その場合、このディレクトリをcomposer.json
のclassmap
ディレクティブへ追加してください。Feel
free to create a new
app/Models
directory to house
your Eloquent
models. Again, add
this directory to
the
classmap
directive of your
composer.json
file.
SoftDeletingTrait
を使用しているモデルでは、Illuminate\Database\Eloquent\SoftDeletes
を使うように変更します。Update
any models using
SoftDeletingTrait
to use
Illuminate\Database\Eloquent\SoftDeletes
.
EloquentキャッシュEloquent Caching
Eloquentは、クエリ結果をキャッシュするためのremember
メソッドを提供しなくなりました。Cache::remember
機能を使用し、手動でクエリをキャッシュする必要があります。キャッシュの詳細は、ドキュメントに全て記載されています。Eloquent
no longer provides
the
remember
method for caching
queries. You now are
responsible for
caching your queries
manually using the
Cache::remember
function. For more
information on
caching, consult the
full
documentation[/docs/{{version}}/cache].
User認証モデルUser Authentication Model
User
モデルをLaravel5の認証システム向けにアップグレードするには、以下の指示に従ってください。To
upgrade your
User
model for Laravel
5's authentication
system, follow these
instructions:
useブロックから、以下の行を削除するDelete
the following
from your
use
block:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
useブロックに、以下の行を追加するAdd
the following to
your
use
block:
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
UserInterfaceとRemindableInterfaceインターフェイスを削除するRemove the UserInterface and RemindableInterface interfaces.
クラスで以下のインターフェイスを実装宣言するMark the class as implementing the following interfaces:
implements AuthenticatableContract, CanResetPasswordContract
クラスの宣言で、以下のトレイトを取り込むInclude the following traits within the class declaration:
use Authenticatable, CanResetPassword;
この方法を取る場合、クラスのuse宣言ブロックから、Illuminate\Auth\Reminders\RemindableTrait
とIlluminate\Auth\UserTrait
を取り除いてください。If
you used them,
remove
Illuminate\Auth\Reminders\RemindableTrait
and
Illuminate\Auth\UserTrait
from your use
block and your
class
declaration.
Cashierの変更Cashier User Changes
Laravel
Cashierで使用されていたトレイトとインターフェイスの名前が変更されました。BillableTrait
の代わりに、Laravel\Cashier\Billable
トレイトを使用してください。それとLarave\Cashier\BillableInterface
の代わりに、Laravel\Cashier\Contracts\Billable
インターフェイスを実装します。他の名前の変更はありません。The
name of the trait
and interface used
by Laravel
Cashier[/docs/{{version}}/billing]
has changed. Instead
of using
BillableTrait
,
use the
Laravel\Cashier\Billable
trait. And, instead
of
Laravel\Cashier\BillableInterface
implement the
Laravel\Cashier\Contracts\Billable
interface instead.
No other method
changes are
required.
ArtisanコマンドArtisan Commands
古いapp/commands
ディレクトリからコマンドクラスを全部、新しいapp/Console/Commands
ディレクトリへ移動します。次に、composer.json
ファイルのclassmap
ディレクティブに、app/Console/Commands
を追加します。Move
all of your command
classes from your
old
app/commands
directory to the new
app/Console/Commands
directory. Next, add
the
app/Console/Commands
directory to the
classmap
directive of your
composer.json
file.
次に、start/artisan.php
のArtisanコマンドリストをapp/Console/Kernel.php
ファイルのcommand
配列へコピーしてください。Then,
copy your list of
Artisan commands
from
start/artisan.php
into the
commands
array of the
app/Console/Kernel.php
file.
データベースのマイグレーションとシーディングDatabase Migrations & Seeds
データベースにusersテーブルが既に存在しているでしょうから、Laravel5.0に含まれている2つのマイグレーションを削除します。Delete the two migrations included with Laravel 5.0, since you should already have the users table in your database.
app/database/migrations
ディレクトリのマイグレートクラスを、新しいdatabase/migrations
へ移動します。初期値設定(seed)クラスをapp/database/seeds
から、database/seeds
へ移動します。Move
all of your
migration classes
from the old
app/database/migrations
directory to the new
database/migrations
.
All of your seeds
should be moved from
app/database/seeds
to
database/seeds
.
グローバルIoC結合Global IoC Bindings
start/global.php
の中のIoC結合は全て、app/Providers/AppServiceProvider.php
ファイルのregister
メソッドへ移動します。App
ファサードをインポートする必要があります。If
you have any
service
container[/docs/{{version}}/container]
bindings in
start/global.php
,
move them all to the
register
method of the
app/Providers/AppServiceProvider.php
file. You may need
to import the
App
facade.
そうした結合定義をカテゴリー毎に別々のサービスプロバイダへ分割する選択肢もあります。Optionally, you may break these bindings up into separate service providers by category.
ビューViews
app/views
中のビューを新しいresources/views
ディレクトリへ移動します。Move
your views from
app/views
to the new
resources/views
directory.
Bladeタグ変更Blade Tag Changes
デフォルトでもセキュリティーを強化するために、Laravel5.0では{{
}}
と{{{
}}}
の両Blade記法で出力がエスケープされます。新しい{!!
!!}
記法により、出力をエスケープせずにそのまま表示します。アプリケーションをアップデートする場合の一番安全な選択肢は、明らかにそのまま出力をしても安全なところでだけで、新しい{!!
!!}
記法を使うことでしょう。For
better security by
default, Laravel 5.0
escapes all output
from both the
{{ }}
and {{{
}}}
Blade
directives. A new
{!! !!}
directive has been
introduced to
display raw,
unescaped output.
The most secure
option when
upgrading your
application is to
only use the new
{!! !!}
directive when you
are
certain
that it is safe to
display raw
output.
しかし、古いBlade記法を使わなくてはならないのでしたら、AppServiceProvider@register
の最後に、以下の数行を追加してください。However,
if you
must
use the old Blade
syntax, add the
following lines at
the bottom of
AppServiceProvider@register
:
\Blade::setRawTags('{{', '}}');
\Blade::setContentTags('{{{', '}}}');
\Blade::setEscapedContentTags('{{{', '}}}');
これは気軽に行うべきではありません。XSS攻撃に対しアプリケーションを脆弱にしてしまうかもしれません。また、{{--
を使用したコメントは廃止されました。This
should not be done
lightly, and may
make your
application more
vulnerable to XSS
exploits. Also,
comments with
{{--
will no longer
work.
言語ファイルTranslation Files
app/lang
下の言語ファイルは、新しいresources/lang
ディレクトリへ移動します。Move
your language files
from
app/lang
to the new
resources/lang
directory.
PublicディレクトリPublic Directory
4.2
アプリケーションのpublic
ディレクトリから、公開しているアセットを新しいアプリケーションのpublic
ディレクトリへコピーします。5.0
バージョンのindex.php
は変更しないように気をつけてください。Copy
your application's
public assets from
your
4.2
application's
public
directory to your
new application's
public
directory. Be sure
to keep the
5.0
version of
index.php
.
テストTests
app/tests
からテストを、新しいtests
ディレクトリへ移動します。Move
your tests from
app/tests
to the new
tests
directory.
その他のファイルMisc. Files
プロジェクトの他のファイルをコピーしましょう。例えば、.scrutinizer.yml
、bower.json
、その他の似たようなツールの設定ファイルなどです。Copy
in any other files
in your project. For
example,
.scrutinizer.yml
,
bower.json
and other similar
tooling
configuration
files.
SassやLess、CoffeeScriptをお好きな場所へ移動しましょう。resources/assets
ディレクトリがデフォルトの場所として最適でしょう。You
may move your Sass,
Less, or
CoffeeScript to any
location you wish.
The
resources/assets
directory could be a
good default
location.
FormとHTMLヘルパForm & HTML Helpers
FormかHTMLヘルパを使用している場合、class
'Form' not
found
かclass
'Html' not
found
のエラーになります。FormとHTMLヘルパはLaravel5.0には含まれなくなりました。しかし、Laravel
Collectiveによりメンテナンスされているコミュニティー主体の代替パッケージが存在しています。If
you're using Form or
HTML helpers, you
will see an error
stating class
'Form' not
found
or
class 'Html'
not
found
.
The Form and HTML
helpers have been
deprecated in
Laravel 5.0;
however, there are
community-driven
replacements such as
those maintained by
the Laravel
Collective[http://laravelcollective.com/docs/{{version}}/html].
例えば、"laravelcollective/html":
"~5.0"
をcomposer.json
のrequire
セクションへ追加してください。For
example, you may add
"laravelcollective/html":
"~5.0"
to your
composer.json
file's
require
section.
それから、FormとHTMLファサードとサービスプロバイダを追加する必要があります。config/app.php
を編集し、providers
配列に以下の行を追加します。You'll
also need to add the
Form and HTML
facades and service
provider. Edit
config/app.php
and add this line to
the 'providers'
array:
'Collective\Html\HtmlServiceProvider',
次に、aliases
配列へ以下を追加します。Next,
add these lines to
the 'aliases'
array:
'Form' => 'Collective\Html\FormFacade',
'Html' => 'Collective\Html\HtmlFacade',
キャッシュマネージャーCacheManager
Laravelのキャッシュでファサードを使用せず、Illuminate\Cache\CacheManager
をコードで注入している場合、代わりにIlluminate\Contracts\Cache\Repository
を注入してください。If
your application
code was injecting
Illuminate\Cache\CacheManager
to get a non-Facade
version of Laravel's
cache, inject
Illuminate\Contracts\Cache\Repository
instead.
ペジネーションPagination
$paginator->links()
の呼び出しを$paginator->render()
へ変更してください。Replace
any calls to
$paginator->links()
with
$paginator->render()
.
$paginator->getFrom()
と$paginator->getTo()
の呼び出しをそれぞれ$paginator->firstItem()
と$paginator->lastItem()
へ置き換えてください。Replace
any calls to
$paginator->getFrom()
and
$paginator->getTo()
with
$paginator->firstItem()
and
$paginator->lastItem()
respectively.
$paginator->getPerPage()
、$paginator->getCurrentPage()
、
$paginator->getLastPage()
、$paginator->getTotal()
の呼び出しから、"get"プレフィックスを取り除いてください。(例:$paginator->perPage()
)Remove
the "get"
prefix from calls to
$paginator->getPerPage()
,
$paginator->getCurrentPage()
,
$paginator->getLastPage()
and
$paginator->getTotal()
(e.g.
$paginator->perPage()
).
BeanstalkキューBeanstalk Queuing
Laravel5.0では、"pda/pheanstalk":
"~2.1"
の代わりに、"pda/pheanstalk":
"~3.0"
が必要になります。Laravel
5.0 now requires
"pda/pheanstalk":
"~3.0"
instead of
"pda/pheanstalk":
"~2.1"
.
RemoteRemote
Remoteコンポーネントは廃止されました。The Remote component has been deprecated.
WorkbenchWorkbench
Workbenchコンポーネントは廃止されました。The Workbench component has been deprecated.
4.1から4.2へのアップグレードUpgrading To 4.2 From 4.1
PHP 5.4 PHP 5.4
Laravel4.2を動作させるにはPHP 5.4.0以上が必要です。Laravel 4.2 requires PHP 5.4.0 or greater.
暗号化のデフォルトEncryption Defaults
app/config/app.php
設定ファイルに、新しいcipher
オプションが追加されました。このオプションの値は、MCRYPT_RIJNDAEL_256
にすべきでしょう。Add
a new
cipher
option in your
app/config/app.php
configuration file.
The value of this
option should be
MCRYPT_RIJNDAEL_256
.
'cipher' => MCRYPT_RIJNDAEL_256
この設定は、Laravelの暗号機能により使用される、デフォルトcipherをコントロールするために使用されます。This setting may be used to control the default cipher used by the Laravel encryption facilities.
Note:
Laravel4.2のデフォルトcipherは、最もセキュアなcipherと考えられているMCRYPT_RIJNDAEL_128
(AES)です。cipherをMCRYPT_RIJNDAEL_256
へ戻すには、Laravel4.1以下で暗号化されたクッキー/値を解読する必要があります。{note} In Laravel 4.2, the default cipher isMCRYPT_RIJNDAEL_128
(AES), which is considered to be the most secure cipher. Changing the cipher back toMCRYPT_RIJNDAEL_256
is required to decrypt cookies/values that were encrypted in Laravel <= 4.1
ソフトデリートは、トレイトを使用するようになりましたSoft Deleting Models Now Use Traits
モデルのソフトデリートを使用している場合、softDeletes
プロパティーは必要なくなりました。SoftDeletingTrait
を次のように使用してください。If
you are using soft
deleting models, the
softDeletes
property has been
removed. You must
now use the
SoftDeletingTrait
like so:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class User extends Eloquent
{
use SoftDeletingTrait;
}
それから、dates
プロパティーにdeleted_at
カラムを追記してください。You
must also manually
add the
deleted_at
column to your
dates
property:
class User extends Eloquent
{
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
ソフトデリート操作のAPIは、今までと変わりありません。The API for all soft delete operations remains the same.
Note:
SoftDeletingTrait
はベースモデルに適用できません。実際のモデルクラスでuseしてください。{note} TheSoftDeletingTrait
can not be applied on a base model. It must be used on an actual model class.
View/PaginationのEnvironmentクラスの名前変更View / Pagination Environment Renamed
もし、Illuminate\View\Environment
クラスか、Illuminate\Pagination\Environment
クラスを直接参照している場合、Illuminate\View\Factory
とIlluminate\Pagination\Factory
を代わりに参照するように、コードを変更してください。この2つのクラスは、機能をより良く表すように名前が変更されました。If
you are directly
referencing the
Illuminate\View\Environment
class or
Illuminate\Pagination\Environment
class, update your
code to reference
Illuminate\View\Factory
and
Illuminate\Pagination\Factory
instead. These two
classes have been
renamed to better
reflect their
function.
ペジネーションプレゼンテーターの引数追加Additional Parameter On Pagination Presenter
Illuminate\Pagination\Presenter
クラスを拡張している場合、getPageLinkWrapper
抽象メソッドに、rel
引数を追加するように変更してください。If
you are extending
the
Illuminate\Pagination\Presenter
class, the abstract
method
getPageLinkWrapper
signature has
changed to add the
rel
argument:
abstract public function getPageLinkWrapper($url, $page, $rel = null);
Iron.Ioキューの暗号化Iron.Io Queue Encryption
Iron.ioキュードライバを使用している場合、新しいencrypt
オプションをキュー設定ファイルに追加する必要があります。If
you are using the
Iron.io queue
driver, you will
need to add a new
encrypt
option to your queue
configuration
file:
'encrypt' => true
4.1.x以下から4.1.29へのアップグレードUpgrading To 4.1.29 From <= 4.1.x
Laravel4.1.29では、全データベースドライバのカラムクオーティングが向上しました。Eloquentモデルにfillable
を使用していない場合の、複数代入に関する脆弱性からアプリケーションを保護します。複数代入されるのを防ぐためにモデルにfillable
プロパティを使用している場合には、アプリケーションに脆弱性はありません。しかし、guarded
を使用し、ユーザがコントロールできる配列を"update"や"save”タイプの機能に渡しているのでしたら、複数代入のリスクにアプリケーションがさらされているため、4.1.29
へすぐアップグレードすべきでしょう。Laravel
4.1.29 improves the
column quoting for
all database
drivers. This
protects your
application from
some mass assignment
vulnerabilities when
not
using the
fillable
property on models.
If you are using the
fillable
property on your
models to protect
against mass
assignment, your
application is not
vulnerable. However,
if you are using
guarded
and are passing a
user controlled
array into an
"update"
or "save"
type function, you
should upgrade to
4.1.29
immediately as your
application may be
at risk of mass
assignment.
Laravel4.1.29へアップグレードするには、composer
update
を実行するだけです。このリリースには、ソース修正が必要な変更は含まれていません。To
upgrade to Laravel
4.1.29, simply
composer
update
.
No breaking changes
are introduced in
this
release.
4.1.25以下から、4.1.26へのアップグレードUpgrading To 4.1.26 From <= 4.1.25
Laravel 4.1.26では、"Remember me"クッキーへのセキュリティーが強化されました。このアップデート以前は、Remeberクッキーが悪意のあるユーザによりハイジャックされ、本当のユーザがアカウントのパスワードをリセットしたり、ログアウトしたりしても、クッキーが長期に渡り有効なままにされてしまいました。Laravel 4.1.26 introduces security improvements for "remember me" cookies. Before this update, if a remember cookie was hijacked by another malicious user, the cookie would remain valid for a long period of time, even after the true owner of the account reset their password, logged out, etc.
今回の変更により、users
テーブル(もしくはユーザ管理を行うためのテーブル)へ、新しいremember_token
カラムを追加する必要があります。この変更により、ユーザがアプリケーションにログインするたびに、真新しいトークンが割り当てられます。このトークンはユーザがアプリケーションからログアウトするたびに、再生成されます。この実装により、もしも"Remember
me"クッキがーハイジャックされても、アプリケーションからログアウトすれば、そのクッキーは無効になります。This
change requires the
addition of a new
remember_token
column to your
users
(or equivalent)
database table.
After this change, a
fresh token will be
assigned to the user
each time they login
to your application.
The token will also
be refreshed when
the user logs out of
the application. The
implications of this
change are: if a
"remember
me" cookie is
hijacked, simply
logging out of the
application will
invalidate the
cookie.
アップデート法Upgrade Path
最初に、新しいremember_token
(null値可能なVARCHAR(100)かTEXTなど)カラムをusers
テーブルに追加してください。First,
add a new, nullable
remember_token
of VARCHAR(100),
TEXT, or equivalent
to your
users
table.
次に、Eloquent認証ドライバを使用しているのであれば、User
クラスへ以下の3クラスを追加してください。Next,
if you are using the
Eloquent
authentication
driver, update your
User
class with the
following three
methods:
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
Note: {note} All existing "remember me" sessions will be invalidated by this change, so all users will be forced to re-authenticate with your application.
この変更により、現在使用中の"Remember me"セッションは無効となるため、全ユーザはアプリケーションへの再認証を強制されます。
パッケージメンテナーの方へPackage Maintainers
Illuminate\Auth\UserProviderInterface
へ、新しいメソッドが2つ追加されました。実装のサンプルは、デフォルトドライバをご覧ください。Two
new methods were
added to the
Illuminate\Auth\UserProviderInterface
interface. Sample
implementations may
be found in the
default
drivers:
public function retrieveByToken($identifier, $token);
public function updateRememberToken(UserInterface $user, $token);
Illuminate\Auth\UserInterface
にも、「アップデート法」で説明している、新しい3つのメソッドが追加されました。The
Illuminate\Auth\UserInterface
also received the
three new methods
described in the
"Upgrade
Path".
4.0から4.1へアップグレードUpgrading To 4.1 From 4.0
Composer依存パッケージのアップグレードUpgrading Your Composer Dependency
アプリケーションをLaravel4.1へアップグレードするには、composer.json
ファイルの中のlaravel/framework
のバージョンを4.1に変更します。To
upgrade your
application to
Laravel 4.1, change
your
laravel/framework
version to
4.1.*
in your
composer.json
file.
ファイルの置き換えReplacing Files
public/index.php
ファイルをリポジトリーのこのファイルで置き換えてください。Replace
your
public/index.php
file with this
fresh copy from
the
repository[https://github.com/laravel/laravel/blob/v4.1.0/public/index.php].
artisan
ファイルをリポジトリーのこのファイルで置き換えてください。Replace
your
artisan
file with this
fresh copy from
the
repository[https://github.com/laravel/laravel/blob/v4.1.0/artisan].
設定ファイルとオプションの追加Adding Configuration Files & Options
app/config/app.php
設定ファイル中のaliases
とproviders
配列を更新します。変更する内容はこのファイルで確認して下さい。自分で追加したサービスプロバーダーとエイリアスを書き戻すのを忘れないで下さい。Update
your
aliases
and
providers
arrays in your
app/config/app.php
configuration file.
The updated values
for these arrays can
be found in this
file[https://github.com/laravel/laravel/blob/v4.1.0/app/config/app.php].
Be sure to add your
custom and package
service providers /
aliases back to the
arrays.
新規にapp/config/remote.php
ファイルをこのリポジトリーから取得し、追加して下さい。Add
the new
app/config/remote.php
file from the
repository[https://github.com/laravel/laravel/blob/v4.1.0/app/config/remote.php].
app/config/session.php
ファイルへ新しいexpire_on_close
設定オプションを追加して下さい。デフォルト値はfalse
です。Add
the new
expire_on_close
configuration option
to your
app/config/session.php
file. The default
value should be
false
.
app/config/queue.php
ファイルへ新しいfailed
設定セクションを追加して下さい。セクションのデフォルト値は以下の通りです。Add
the new
failed
configuration
section to your
app/config/queue.php
file. Here are the
default values for
the
section:
'failed' => [
'database' => 'mysql', 'table' => 'failed_jobs',
],
(オプション):app/config/view.php
ファイル中のpagination
設定オプションをpagination::slider-3
に変更することもできます。(Optional)
Update the
pagination
configuration option
in your
app/config/view.php
file to
pagination::slider-3
.
コントローラーの更新Controller Updates
もし、app/controllers/BaseController.php
が頭のところでuse
文を使用していたら、use
Illuminate\Routing\Controllers\Controller;
をuse
Illuminate\Routing\Controller;
へ変更して下さい。If
app/controllers/BaseController.php
has a
use
statement at the
top, change
use
Illuminate\Routing\Controllers\Controller;
to use
Illuminate\Routing\Controller;
.
パスワードリマインダーの更新Password Reminders Updates
パスワードリマインダーは自由度を増すために全体的に見なおされました。php
artisan
auth:reminders-controller
Artisanコマンドを実行し、作成される新しいスタブコントローラーを調べてみて下さい。もしくは、更新されたドキュメントを読み、それに従ってアプリケーションを更新して下さい。Password
reminders have been
overhauled for
greater flexibility.
You may examine the
new stub controller
by running the
php artisan
auth:reminders-controller
Artisan command. You
may also browse the
updated
documentation[/docs/security#password-reminders-and-reset]
and update your
application
accordingly.
app/lang/en/reminders.php
言語ファイルをこちらの更新済みファイルに合わせて変更して下さい。Update
your
app/lang/en/reminders.php
language file to
match this
updated
file[https://github.com/laravel/laravel/blob/v4.1.0/app/lang/en/reminders.php].
環境決定の更新Environment Detection Updates
セキュリティーの観点から、アプリケーションの環境を決定するためにURLのドメインはもう使用されなくなりました。これらの値は簡単に偽装でき、リクエストの環境を変更する攻撃が可能です。コンピューターのホスト名を利用するように、環境決定コードを変更して下さい。(hostname
コマンドがMac、Linux、Windowsで使用できます。)For
security reasons,
URL domains may no
longer be used to
detect your
application
environment. These
values are easily
spoofable and allow
attackers to modify
the environment for
a request. You
should convert your
environment
detection to use
machine host names
(hostname
command on Mac,
Linux, and
Windows).
ログファイルの単純化Simpler Log Files
今回よりLaravelは、app/storage/logs/laravel.log
ファイルのみを作成、使用するようになりました。しかし、この動作はapp/start/global.php
ファイルで設定できるままになっています。Laravel
now generates a
single log file:
app/storage/logs/laravel.log
.
However, you may
still configure this
behavior in your
app/start/global.php
file.
Trailing Slashリダイレクトの削除Removing Redirect Trailing Slash
bootstrap/start.php
ファイルの中から、$app->redirectIfTrailingSlash()
の呼び出しを削除して下さい。この機能はフレームワークに含まれている.htaccess
ファイルで処理されるようになったため、メソッドは必要なくなりました。In
your
bootstrap/start.php
file, remove the
call to
$app->redirectIfTrailingSlash()
.
This method is no
longer needed as
this functionality
is now handled by
the
.htaccess
file included with
the
framework.
次に、Apacheの.htaccess
ファイルを最後のスラッシュを処理する新バージョンへ置き換えて下さい。Next,
replace your Apache
.htaccess
file with this
new
one[https://github.com/laravel/laravel/blob/v4.1.0/public/.htaccess]
that handles
trailing
slashes.
現在のルートへのアクセスCurrent Route Access
現在のルートへアクセスするには、Route::getCurrentRoute()
の代わりに、Route::current()
が使えるようになりました。The
current route is now
accessed via
Route::current()
instead of
Route::getCurrentRoute()
.
Composerの更新Composer Update
以上の変更を行ったら、アプリケーションのコアファイルを更新するために、composer
update
を実行して下さい!クラスのロードエラーになった場合は、update
コマンドを--no-scripts
オプションを付け、実行してみてください。ですから、composer
update
--no-scripts
と実行します。Once
you have completed
the changes above,
you can run the
composer
update
function to update
your core
application files!
If you receive class
load errors, try
running the
update
command with the
--no-scripts
option enabled like
so: composer
update
--no-scripts
.
ワイルドカードイベントリスナWildcard Event Listeners
ワイルドカードイベントリスナは、ハンドラ関数の引数にイベントを渡さなくなりました。発行されたイベントを見つける必要がある場合は、Event::firing()
を使用してください。The
wildcard event
listeners no longer
append the event to
your handler
functions
parameters. If you
require finding the
event that was fired
you should use
Event::firing()
.