douguwo2275 2014-09-21 22:48
浏览 158
已采纳

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

I have just started learning Laravel and would like to know if it is possible to create a Route::resource that would allow me to access the below URL using RESTful methods:

I would like the URL to look like this:

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

And I would like to access this from my ArticlesController using:

//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);
}

From what I've gathered so far, this can somehow be accomplished by doing something like the below in the routes.php file:

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

But that doesn't quite look right to me.

Does anyone have any suggestions?

  • 写回答

1条回答 默认 最新

  • duanjiu2701 2014-09-21 23:00
    关注

    Resource controllers are useful for building RESTful controllers that form the backbone of APIs. The general syntax is this:

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

    This will create seven different routes in a single call, but is really just a convenience method for doing this:

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

    The URLs are only based off of the resource's name that you specify, and the method names are built in. I am not aware of any way that you can modify those using resource controllers.

    If you want pretty URLs, then assign those routes without using a resource controller:

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

    Note that if you do use the show method, this will conflict with any REST-ful URL that you may have defined previously (the show method in a resource controller will only expect 1 parameter passed in, namely the ID of the resource to show). For this reason I would recommend you to change the name of that method to something else.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题