doubianyu7844 2015-01-29 20:49 采纳率: 0%
浏览 31
已采纳

Laravel相互冲突的路线

My routes.php excerpt:

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {

    Route::resource('posts', 'PostsController', [
        'except' => ['show']
    ]);

    Route::delete('posts/trash', [
        'as' => 'posts.trash.empty',
        'uses' => 'PostsController@emptyTrash'
    ]);

});

My PostsController.php excerpt:

/**
 * DELETE /admin/posts/{id}
 */
public function destroy($id)
{
    // code
}

/**
 * DELETE /admin/posts/trash
 */
public function emptyTrash()
{
    // code
}

The problem is that Laravel confuses the 'trash' string in a DELETE /admin/posts/trash request as an {id} parameter. As a consequence, the destroy() method is called instead of emptyTrash(). Why and What can I do for this?

  • 写回答

2条回答 默认 最新

  • doujie1908 2015-01-29 21:27
    关注

    Firstly, order matters. Laravel will search the routes for a match in the order you register them. As you figured out, Laravel will take trash as an id and therefore the URI matches the resource route. Since that route is registered before your additional one, it will use the resource route.

    The simplest fix is to just change that order:

    Route::delete('posts/trash', [
        'as' => 'posts.trash.empty',
        'uses' => 'PostsController@emptyTrash'
    ]);
    
    Route::resource('posts', 'PostsController', [
        'except' => ['show']
    ]);
    

    If you don't like that you can try to limit the parameter for your resource route to numbers only. Unfortunately you can't just add a ->where() to the resource route like you could with others.

    Instead you have to define a global pattern for the route parameter. The route parameter Route::resource chooses is the resource name (in snake_case).

    So this should work for you:

    Route::pattern('posts', '[0-9]+');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据