使用 Laravel 的 Route::resource RESTful 方法的漂亮 URL

Nic*_*Law 3 php rest url laravel

我刚刚开始学习 Laravel,想知道是否可以创建一个 Route::resource 来允许我使用 RESTful 方法访问以下 URL:

我希望 URL 看起来像这样:

http://example.com/articles/2014/09/22/this-is-the-article-title
Run Code Online (Sandbox Code Playgroud)

我想使用以下方法从我的 ArticlesController 访问它:

//GET articles/{year}/{month}/{day}/{title}
public function show($year, $month, $day, $title) {
    $article = //find article in DB
    return View::make('articles.show')->with('article', $article);
}
Run Code Online (Sandbox Code Playgroud)

根据我到目前为止收集到的信息,这可以通过在 paths.php 文件中执行如下操作来完成:

Route::resource('year.month.day.articles', 'ArticlesController');
Run Code Online (Sandbox Code Playgroud)

但这对我来说看起来不太正确。

有没有人有什么建议?

Jef*_*ert 5

资源控制器对于构建构成 API 主干的 RESTful 控制器非常有用。一般语法是这样的:

Route::resource('resourceName', 'ControllerName');
Run Code Online (Sandbox Code Playgroud)

这将在一次调用中创建七个不同的路由,但这实际上只是执行此操作的一种便捷方法:

Route::get('/resourceName',                 'ControllerName@index');
Route::get('/resourceName/{resource}',      'ControllerName@show');
Route::get('/resourceName/create',          'ControllerName@create');
Route::get('/resourceName/{resource}/edit', 'ControllerName@edit');
Route::post('/resourceName',                'ControllerName@store');
Route::put('/resourceName/{resource}',      'ControllerName@update');
Route::delete('/resourceName/{resource}',   'ControllerName@destroy');
Run Code Online (Sandbox Code Playgroud)

URL基于您指定的资源名称,并且方法名称是内置的。我不知道您可以使用资源控制器修改这些名称。

如果您想要漂亮的 URL,请在不使用资源控制器的情况下分配这些路由:

Route::get('/articles/{year}/{month}/{day}/{title}', 'ArticlesController@show');
Run Code Online (Sandbox Code Playgroud)

请注意,如果您确实使用该show方法,这将与您之前定义的任何 REST-ful URL 冲突(show资源控制器中的方法将只需要传入 1 个参数,即要显示的资源的 ID)。因此,我建议您将该方法的名称更改为其他名称。