2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】ルート定義を正規表現付きで設定するには

Posted at

正規表現の制約設定

Laravelでは、ルートを定義するファイルroutes/web.phpに正規表現を利用してルート定義できます。ルートインスタンスのwhereメソッドを使用しましょう。
第1引数に制約設定をしたいパラメータ名、第2引数に正規表現を記入します。

(例1)routes/web.php
Route::get('user/{name}', function ($name) {
    // 
})->where('name', '[A-Za-z]+');

nameパラメータは、小文字a~z、大文字A~Zで1文字以上であること
 

(例2)routes/web.php
Route::get('user/{id}', function ($id) {
    //
})->where('id', '[0-9]+');

idパラメータは、数字0~9で1文字以上であること
 

(例3)routes/web.php
Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

idパラメータは、数字0~9で1文字以上であること
nameパラメータは、小文字a~zで1文字以上であること

例3ではwhereメソッドに連想配列を入れて制約設定を行っています。
キーにパラメータ名、値に正規表現という感じです。

上記の各々の例を参考に、パラメータの制約が設定できます。「自分で定めた設定のパラメータを正規表現で設定したいんや~!」というときに、このwhereメソッドを活用しましょう。:grinning:

グローバル制約

ルート定義ファイルroutes/web.phpwhereメソッドを使用して、1個ずつルートの制約設定をするのも良いですが、指定した正規表現を、ルート定義した全部のルートパラメータに適応させたい場合はapp/Providers/RouteServiceProvider.phpbootメソッド内で設定を行いましょう。

app/Providers/RouteServiceProvider.php
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        Route::pattern('id', '[0-9]+'); // 追加した部分
        parent::boot();
    }

Route::pattern('id', '[0-9]+');の部分を追加することで、idパラメータを使用している全ルートで、自動的に「0~9の数字で1文字以上」という制約がかかります。

2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?