2021-06-03
Laravel
Preventing Lazy Loading DBの遅延読み込み防止
4年前の記事です。
Laravelは古い情報は全く役に立たないので絶対に参考にしないでください。
コメントに新しい情報がないか確認してください。
ドキュメント以外に必要な情報は特にない。
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
バージョン
Laravel 8.44.0以降。
使い方
AppServiceProvider@bootで
use Illuminate\Database\Eloquent\Model;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Model::preventLazyLoading(! $this->app->isProduction());
}
これで遅延読み込みがあれば例外で落ちるのですぐ分かる。
本番環境では仮に遅延読み込みが残っていても何も起きない。あくまでパフォーマンスの違いなので本番環境でエラー画面を出すよりはそのままのほうがいい。
余談
本番用のAPP_ENVはproduction、もしくはAPP_ENVを指定しない。
config/app.phpでは'env' => env('APP_ENV', 'production'),なので指定しなければproduction。
APP_ENVを勝手にprodとかdevとか設定してる人をよく見る。これも「他のフレームワークの知識だけでLaravelを使ってる時のよくある間違い」
local production testingはLaravel内で定義されてる定数みたいなもの。
public function isLocal()
{
return $this['env'] === 'local';
}
public function isProduction()
{
return $this['env'] === 'production';
}
public function runningUnitTests()
{
return $this['env'] === 'testing';
}
違うAPP_ENVを設定してもいいけどLaravelの標準ではないと理解した上で使う。