LoginSignup
4
5

More than 3 years have passed since last update.

【Laravel】ルート名を使って条件分岐をする方法。ページごとに処理を切り分ける。

Posted at

ページによって処理を切り分けたい場合、ルート名を使うことで簡単に実現できる。

Request::routeIs('ルート名')
- RequestファサードのrouteIsメソッド
- 指定したルート名の場合はtrue、それ以外の場合はfalseとなる。


使い方(.blade.php)
        @if( Request::routeIs('english'))
          <h1>Hello!!!</h1>
        @endif

ルート名が、englishのとき、h1タグを表示する処理となる。

ルーティング(web.php)
Route::get('greetings/english', 'GreetingController@english')->name('english');

->name('english')でルート名を指定している。


使いどころ

条件分岐をページ固有の変数(例えばテキスト)で指定すると、変数の中身が変わったときに、処理が適用されなくなってしまう。

なのでページによって切り分ける場合は、Request::routeIsメソッドを使う。

NG事例
        @if( $language === "english" ))
          <h1>Hello!!!</h1>
        @endif

変数$languageの値が、「英語」や「eng」になった場合に適用されなくなる。


(補足)パスで処理を切り分ける場合

ルート名ではなくパスで切り分ける場合は、Route::is()を使う。

使い方(.blade.php)
        @if( Request::is(/greetings/english))
          <h1>Hello!!!</h1>
        @endif
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5