问题
I'm creating an api with Laravel and I am looking for a easy lazy way to to register Api resources. I'm currently defining my routes like this:
Route::apiResoruce('categories', 'CategoryController')->only(['index', 'show']);
I checked Laravel's controller documentation and I saw apiResources
method which I can create multiple api resources at once.
the goal:
is to be able to use apiResources
with only
method like this
Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);
current result:
Call to a member function only() on null
回答1:
long story short (if you don't want to read the whole story) you can just do it like this:
Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);
When I was writing the question it passed to my mind to check the apiResources
declaration and I found this:
/**
* 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);
}
}
and since it is using apiResource
under the hood and it is passing options parameter I can check what are these options
/**
* 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));
}
来源:https://stackoverflow.com/questions/62099850/how-to-use-apireources-method-with-only