今までコントローラやビューの中で URL を指定する時は、ソースコードに直にパスを書いていました。しかし、この方法だと、パスに変更があった時に、多くの箇所を変更しなければなりません。そこで、ルートに名前を付け、ルート名で URL を指定することで、この問題を解決したいと思います。
名前付きルートの設定
ルートに名前を付けるよう routes/web.php を修正します。
// app/Http/routes.php ... // 名前を指定した Route の書き方 Route::get('/', 'WelcomeController@index')->name('home'); Route::get('contact', 'PagesController@contact')->name('contact'); Route::get('about', 'PagesController@about')->name('about'); Route::get('articles', 'ArticlesController@index')->name('articles.index'); Route::get('articles/create', 'ArticlesController@create')->name('articles.create'); Route::get('articles/{id}', 'ArticlesController@show')->name('articles.show'); Route::post('articles', 'ArticlesController@store')->name('articles.store'); Route::get('articles/{id}/edit', 'ArticlesController@edit')->name('articles.edit'); Route::patch('articles/{id}', 'ArticlesController@update')->name('articles.update'); Route::delete('articles/{id}', 'ArticlesController@destroy')->name('articles.destroy');
行末に name() メソッドを追加して、各ルートに名前を付けました。
名前付きルートの使い方
Controller
// app/Http/Controllers/ArticlesController.php ... ... public function store(ArticleRequest $request) { ... // return redirect('articles') return redirect()->route('articles.index') ->with('message', '記事を追加しました。'); } ... ... public function update($id, ArticleRequest $request) { ... // return redirect(url('articles', [$article->id])) return redirect()->route('articles.show', [$article->id]) ->with('message', '記事を更新しました。'); }
redirect で直にパスを書いて指定していたのを、route() メソッドを使って named route に変更しました。
View
// resources/views/articles/create.blade.php @extends('layout') @section('content') <h1>Write a New Article</h1> <hr/> @include('errors.form_errors') {{-- Form::open(['url' => 'articles']) --}} {!! Form::open(['route' => 'articles.store']) !!} @include('articles.form', ['published_at' => date('Y-m-d'), 'submitButton' => 'Add Article']) {!! Form::close() !!} @endsection
Form::open で直に URL パスを書いていたのを、named route に変更しました。
演習
コントローラやビューで URL を指定している箇所を全て、名前付きルートでの指定に変更してみてください。
https://laravel.com/docs/5.6/routing#named-routes
https://laravelcollective.com/docs/master/html#opening-a-form