9
4

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のroutingでprefixにパラメーターを入れる事ができる

Posted at

LaravelでRestAPIライクなURLを設定する時には、prefix内にパラメーターを設定すると子のroute側でパラメーターが受け取れます。

/posts/{id}/comments
/posts/{id}/recommends

というようなAPIを作成するとします。

以下のようにしてRouteのところにidを入れてURLを指定することも出来ますが、

api.php
Route::prefix('posts')->group(function () {
    Route::get('/{id}/comments', 'PostController@comments');
    Route::get('/{id}/recommends', 'PostController@recommends');
});

以下のようにprefixにパラメーターを入れる形でもControllerのメソッド側でidをパラメーターとして受け取ることが出来ます。

api.php
Route::prefix('posts/{id}')->group(function () {
    Route::get('/comments', 'PostController@comments');
    Route::get('/recommends', 'PostController@recommends');
});
9
4
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
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?