【问题标题】:Pretty URL's using Laravel's Route::resource RESTful methods使用 Laravel Route::resource RESTful 方法的漂亮 URL
【发布时间】:2014-09-21 22:48:34
【问题描述】:

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

我希望 URL 看起来像这样:

http://example.com/articles/2014/09/22/this-is-the-article-title

我想从我的 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);
}

根据我目前收集到的信息,这可以通过在 routes.php 文件中执行以下操作来以某种方式完成:

Route::resource('year.month.day.articles', 'ArticlesController');

但这对我来说并不完全正确。

有人有什么建议吗?

【问题讨论】:

    标签: php rest url laravel


    【解决方案1】:

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

    Route::resource('resourceName', 'ControllerName');
    

    这将在一次调用中创建seven different routes,但实际上只是一种方便的方法:

    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');
    

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

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

    Route::get('/articles/{year}/{month}/{day}/{title}', 'ArticlesController@show');
    

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

    【讨论】:

    • 感谢您的回复。我是 RESTful 开发的新手,您的回答有助于澄清我的情况。
    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 2017-06-26
    • 2011-01-16
    • 2014-01-25
    • 2019-06-14
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多