6

I'm creating an api with Laravel and I am looking for an easy lazy way to to register Api resources. I'm currently defining my routes like this:

Route::apiResource('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

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
RoduanKD
  • 1,279
  • 11
  • 27

1 Answers1

10

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));
}
RoduanKD
  • 1,279
  • 11
  • 27
  • The second argument (options) applies to all the resources? I just don't want one of them to use the "update" method. Maybe we can't do it with `apiResources`. – aasutossh May 16 '21 at 05:57
  • No this will be applied only to the resource you are using `apiResource` with. in the answer for **brands** resource, I just needed `index` and `show` methods to be defined by this resource. and the other `apiResource` won't be affected. it depends on the options you're passing to it. – RoduanKD May 16 '21 at 12:36
  • I am talking about `apiResources` not `apiResource`. We are not in the same page. – aasutossh May 17 '21 at 05:57
  • Sorry for misunderstanding first, Yeah you are right about that **options** argument is for all of resources passed in the first argument. – RoduanKD May 17 '21 at 07:17