LoginSignup
0
0

More than 1 year has passed since last update.

Laravelのルーティングにおけるnameメソッドについて

Last updated at Posted at 2022-08-07

はじめに

下記のようにweb.php内のルーティングの設定時に、nameメソッドを使用する用途目的と処理の流れを理解するのためにまとめてみる。

web.php
Route::get('/test/', 'ArticleController@index')->name('testpage');

【さきに結論】

ルーティング側でname()メソッドを設定したら、view側でroute()メソッドの引数にname()メソッドと同じ引数を使用できる。

今回welcome.blade.phpのview側のHTMLのリンクタグ<a href=""></a> でrouteメソッド利用時に引数にurl名をnameメソッドの引数を当てることができることを確認。

なお、viewのテンプレートへのURLの記述をパス表記でなく、name()メソッドで決めた名前を設定することで、ローティングとビューの設定値が同じため、見やすく確認しやすくなり管理しやすくなる。

【利用条件】

Laravel 6
URLのlocalhost:8009がトップページ('/')を表示

【確認】

まず、nameメソッドがない場合の動きを確認

web.php
Route::get('/test/', 'ArticleController@index')

URLの/test/にアクセスすると
ArticleControllerクラスの
indexメソッドが処理され実行し、
indexメソッドはindex.blade.phpを表示させる

【関係ファイル】
1.web.php
2.ArticleController.php
3.index.blade.php
4.welcome.blade.php

【処理の流れを確認】
welcom.blade.phpにあるリンク(<a href=""></a>)をクリックすると、index.blade.phpのページを表示する処理。

web.phpのURL設定

web.php
//トップページを表示
Route::get('/', function () {
    return view('welcome');
});
//nameメソッドを追記
Route::get('/test/', 'ArticleController@index')->name('testpage');

welcome.blade.phpに下記リンクを追加

 welcome.blade.php
<a href="{{ route('testpage') }}">testpage</a>

-【画面確認】
スクリーンショット 2022-08-02 21.35.04.png

-コントローラーとビューに追記

-【Controller】

ArticleController.php
class ArticleController extends Controller
{
    public function index(){
        $id = 123;
        return view('index', ['abc' => $id]);
    }
}

-【View】

index.blade.php
<body>
    <p>テストページ</p> 
    {{ $abc }}
</body>

-TESTPAGEのリンクをクリックし【画面確認】
スクリーンショット 2022-08-07 17.37.33.png

-上記画像のトップデージwelcome.blade.phptestpageのリンクをクリックしたら、http://localhost:8009/testのurlにアクセスできることを確認

【参照】

名前付きルート

0
0
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
0
0