ahoi's avatar
Level 5

Add additional route to Route::apiResource

Hello everybody,

I got this api-routes:

    Route::get('user/pdf/{user}', [UserApiController::class, 'pdf']);

    Route::apiResource('user', UserApiController::class);

This is working fine, but of course the method pdf is not being authorized automagically using authorizeResource:

 public function __construct()
    {
        $this->authorizeResource(User::class, 'user');
    }

Instead I have to do something like this:

    public function pdf(User $user): StreamedResponse
    {
        $this->authorize('view', $user);
        [...]
    }

This works fine, but maybe there's a more elegant way to add another route to Route::apiResource?

0 likes
1 reply
martinbean's avatar

This works fine, but maybe there's a more elegant way to add another route to Route::apiResource?

There isn’t. API resource routes are a predefined set of routes. This is covered in the docs at https://laravel.com/docs/8.x/controllers#restful-supplementing-resource-controllers:

If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to the Route::resource method

The same is true for Route::apiResource too.

Please or to participate in this conversation.