Skip to content

パフォーマンス最適化

<?php
// 設定のキャッシュ
php artisan config:cache
// ルートのキャッシュ
php artisan route:cache
// ビューのキャッシュ
php artisan view:cache
// すべてのキャッシュ
php artisan optimize
<?php
// Eager Loading(N+1問題の解決)
$users = User::with('posts')->get();
// 特定のカラムのみ取得
$users = User::select('id', 'name', 'email')->get();
// チャンク処理
User::chunk(100, function ($users) {
foreach ($users as $user) {
// 処理
}
});
<?php
// マイグレーションでインデックスを追加
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->index('email');
$table->index(['name', 'email']); // 複合インデックス
});
}
<?php
// キャッシュを使用
$users = Cache::remember('users', 3600, function () {
return User::all();
});
// キャッシュの削除
Cache::forget('users');