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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看