はじめに
Laravel9 で便利な機能が追加されました。
僕自身が実際に使ってみて便利だと感じた機能を紹介します。
① コントローラーのグループ化(おすすめ度 ★★)
/* 以前の書き方
--------------------------------------------*/
Route::get("test/index", [TestController::class,'index']);
Route::get("test/show", [TestController::class,'show']);
/* Laravel9では以下のように書くことができる
--------------------------------------------*/
Route::controller(TestController::class)->group(function(){
Route::get('test/index', 'index')->('test.index');
Route::get('test/show', 'show')->('test.show');
});
// 上の内容をGroupでまとめて以下のように書くことも可能
Route::group([
'prefix'=>'test',
'as'=>'test.',
'controller'=>'App\Http\Controllers\TestController'
], function() {
Route::get('index', 'index')->('index');
Route::get('show', 'show')->('show');
});
});
② to_route()を使ったリダイレクト(おすすめ度 ★★★)
/* 以前の書き方
--------------------------------------------*/
return redirect(route('index'));
/* Laravel9では以下のように書くことができる
--------------------------------------------*/
return to_route('index');
③ Checked/SelectedのBlade Directives(おすすめ度 ★★★)
Checked
/* 以前の書き方
--------------------------------------------*/
<input type="checkbox"
name="active"
value="active"
// @ifなどを使用して判定する必要があった
@if(old('active', $user->active) == "active") checked @endif/>
/* Laravel9では以下のように書くことができる
--------------------------------------------*/
<input type="checkbox"
name="active"
value="active"
@checked(old('active', $user->active)) />
Selected
/* 以前の書き方
--------------------------------------------*/
<select name="version">
@foreach ($product->versions as $version)
<option value="{{ $version }}"
// @ifなどを使用して判定する必要があった
@if(old('version') == $version) selected @endif>
{{ $version }}
</option>
@endforeach
</select>
/* Laravel9では以下のように書くことができる
--------------------------------------------*/
<select name="version">
@foreach ($product->versions as $version)
<option value="{{ $version }}"
@selected(old('version') == $version)>
{{ $version }}
</option>
@endforeach
</select>
さいごに
他にも色々と機能は追加になりましたが、個人的にはこの3つをよく使います!
本当にLaravelって便利ですね!