如何将 apiReources 方法与 `only` 一起使用?
how to use apiReources method with `only`?
我正在用 Laravel 创建一个 api,我正在寻找一种简单的懒惰方法来注册 Api 资源。
我目前正在这样定义我的路线:
Route::apiResource('categories', 'CategoryController')->only(['index', 'show']);
我检查了 Laravel's controller documentation,我看到了 apiResources
方法,我可以一次创建多个 api 资源。
目标:
是能够使用 apiResources
和 only
这样的方法
Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);
当前结果:
Call to a member function only() on null
长话短说(如果你不想阅读整个故事)你可以这样做:
Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);
当我写这个问题时,我想到了检查 apiResources
声明,我发现了这个:
/**
* Register an array of API resource controllers.
*
* @param array $resources
* @param array $options
* @return void
*/
public function apiResources(array $resources, array $options = [])
{
foreach ($resources as $name => $controller) {
$this->apiResource($name, $controller, $options);
}
}
并且因为它在幕后使用 apiResource
并且它正在传递选项参数我可以检查这些选项是什么
/**
* Route an API resource to a controller.
*
* @param string $name
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\PendingResourceRegistration
*/
public function apiResource($name, $controller, array $options = [])
{
$only = ['index', 'show', 'store', 'update', 'destroy'];
if (isset($options['except'])) {
$only = array_diff($only, (array) $options['except']);
}
return $this->resource($name, $controller, array_merge([
'only' => $only,
], $options));
}
我正在用 Laravel 创建一个 api,我正在寻找一种简单的懒惰方法来注册 Api 资源。 我目前正在这样定义我的路线:
Route::apiResource('categories', 'CategoryController')->only(['index', 'show']);
我检查了 Laravel's controller documentation,我看到了 apiResources
方法,我可以一次创建多个 api 资源。
目标:
是能够使用 apiResources
和 only
这样的方法
Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);
当前结果:
Call to a member function only() on null
长话短说(如果你不想阅读整个故事)你可以这样做:
Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);
当我写这个问题时,我想到了检查 apiResources
声明,我发现了这个:
/**
* Register an array of API resource controllers.
*
* @param array $resources
* @param array $options
* @return void
*/
public function apiResources(array $resources, array $options = [])
{
foreach ($resources as $name => $controller) {
$this->apiResource($name, $controller, $options);
}
}
并且因为它在幕后使用 apiResource
并且它正在传递选项参数我可以检查这些选项是什么
/**
* Route an API resource to a controller.
*
* @param string $name
* @param string $controller
* @param array $options
* @return \Illuminate\Routing\PendingResourceRegistration
*/
public function apiResource($name, $controller, array $options = [])
{
$only = ['index', 'show', 'store', 'update', 'destroy'];
if (isset($options['except'])) {
$only = array_diff($only, (array) $options['except']);
}
return $this->resource($name, $controller, array_merge([
'only' => $only,
], $options));
}