【问题标题】:nested resources in laravel not workedlaravel 中的嵌套资源不起作用
【发布时间】:2018-06-18 15:45:04
【问题描述】:

我想要这样的嵌套资源:

Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::resource('/articles', 'ArticleController');

   Route::group(['prefix' => '/articles', 'as' => 'articles.'], function () {
        Route::resource('/types', 'ArticleTypeController');
    });
});

但是“文章/类型”的嵌套路由不起作用,我在“文章”路由之外检查了我的 ArticleTypeController 并工作。

我真的很困惑,大家可以帮帮我吗?

这是我的控制器:

class ArticleTypeController extends Controller
{

    public function index()
    {
        $types = ArticleType::all();
        return view('manage.articles.types.index')->withtypes($types);
    }
}

【问题讨论】:

  • /article/type/articles/types?检查您的定义方式并确保使用正确的值(复数与非复数)
  • 不,蒂姆,它是复数形式
  • But nested route for "article/type" doesn't work 这句话有什么问题?该声明应该读作 article/type 还是 articles/types

标签: laravel controller routes


【解决方案1】:
Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::get('articles/types', 'ArticleTypeController@articleTypeMethod');

   Route::resource('articles', 'ArticleController');    
   Route::resource('articles.types', 'ArticleTypeController');
});

对于嵌套资源,请使用articles.types。复数命名是好的。 现在manage/articlesmanage/articles/1/types 可以工作了。

如果要放置自定义路由,如果控制器已用作资源,请将其放在资源路由上方。查看映射到ArticleTypeControllerarticleTypeMethodarticles/types [GET] 路由。现在这种方式http://localhost.com/manage/articles/types 应该可以工作了

这里是5.1 documentation,它已从 5.5 的文档中删除。但是看看泰勒是怎么说的here

不建议在 REST 上对 articles/types 使用索引函数,使用嵌套资源 index 方法,如 articles/{id}/types。 对于articles/types,您需要创建一个新方法。

但如果你仍然想那样做。就这样吧

Route::group(['prefix' => 'manage', 'middleware' => ['role:boss']], function () 
{
   Route::get('articles/types', 'ArticleTypeController@index');

   Route::resource('articles', 'ArticleController');    
   Route::resource('articles.types', 'ArticleTypeController', ['except' => ['index']]);
});

【讨论】:

  • 感谢您的回复,但具体我想使用manage/articles/types,这是我的问题
  • 这就是你想要的吗?
  • 难道不可以使用组或资源吗?
  • 因为它是自定义路由,所以不能用作 REST 资源路由。正如我所提到的,您需要创建一个特定的方法并使用 http 方法调用该路由。资源路由只是索引、创建、存储、编辑、更新、销毁。检查我提供的文档链接:)
  • 我明白了。谢谢!
猜你喜欢
  • 2012-07-07
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多