laravel URLの作成(url()ヘルパ関数、route()ヘルパ関数、名前付きルート、ルートパラメータ)

コントローラー、ビューでURLを作成したい

作成日:2024-02-20, 更新日:2024-02-20

基本

ひとまずルーティングについて

  • routeヘルパー関数を使うにはURLと名前を紐づける必要がある
  • 「xxx/{任意の値}」のようなURLにしたいならルートパラメータの設定が必要

URLの設定

Route::get('/example', 'ExampleController@index');

名前付きルートの設定

Route::get('/example', 'ExampleController@index')->name('routeName');

ルートパラメータの設定

Route::get('/example/{hoge}', 'ExampleController@index');

名前付きルートとルートパラメータの設定

Route::get('/example/{hoge}', 'ExampleController@index')->name('routeName');

コントローラー

ルートで定義したパラメータ名とコントローラーメソッドの引数名をあわせる必要アリ

public function index(Request $request, $hoge){}

urlヘルパー関数

$url = url('example/path');

GETパラメータを追加

$urlWithQuery = url('example/path?hoge=1');

ルートパラメータを追加

$urlWithQuery = url('example/path', [1]);

→出力されるURLは「example/path/1」となる

routeヘルパー関数

URLを名前付きルートに設定している場合、routeヘルパー関数が使える
※「routeName」を名前付きルートに設定している場合

$url = route('routeName');

GETパラメータを追加

ルートパラメータを設定せずに名前付きルートを設定
→「http://xxxx/example?hoge=1」を作成したい

▼routes/web.php

Route::get('/example', 'ExampleController@index')->name('routeName');

▼URLの生成

$urlWithQuery = route('routeName', ['hoge' => 1]);

ルートパラメータを追加

ルートパラメータと名前付きルートを設定
→「http://xxxx/example/1」を作成したい

▼routes/web.php

Route::get('/example/{hoge}', 'ExampleController@index')->name('routeName');

▼URLの生成

$urlWithQuery = route('routeName', [1]);

GETパラメータとルートパラメータを混在させたい

ルートパラメータと名前付きルートを設定
→「http://xxxx/example/1?foo=2」を作成したい

▼routes/web.php

Route::get('/example/{hoge}', 'ExampleController@index')->name('routeName');

▼URLの生成

$urlWithQuery = route('routeName', [1, 'foo'=>2]);

ビューでの出力

BladeテンプレートエンジンのBlade構文(「{{}}」で囲む)で、そのままechoしてくれるし、URLもエスケープ処理してくれる
※routeヘルパ関数も同じように使える

{{ url('example/path') }}

GETパラメータを追加

{{ url('example/path?hoge=1') }}

ルートパラメータを追加

{{ url('example/path', [1]) }}

メモ

▼名前付きルートを下記のような設定にしている場合

Route::get('/home', 'ExampleController@index')->name('home');
記述 結果 メモ
{{ url('/home', [1]) }}
http://xxx/home/1

{{ url('/home', ['a' => 1]) }}
http://xxx/home/1

添え字は無視される
{{ url('/home?a=1') }}
http://xxx/home?a=1

{{ route('home', [1]) }}
http://xxx/home/1 ルートパラメータを設定している場合
{{ route('home', ['a' => 3]) }}
http://xxx/home/3 ルートパラメータを設定している場合、添え字は無視される
{{ route('home', [1]) }}
http://xxx/home/?1 ルートパラメータを設定していない場合、getパラメータの書式になる
{{ route('home', ['a' => 3]) }}
http://xxx/home?a=3 ルートパラメータを設定していない場合、getパラメータの書式になる
{{ route('home', [4, 5]) }}
http://xxx/home/4?5 ルートパラメータを一つだけしている場合、2つ目はgetパラメータの書式になる
{{ route('home', [4, 'b' => 1]) }}
http://xxx/home/4?b=1 ルートパラメータを一つだけしている場合、2つ目はgetパラメータの書式になる

関連項目