anonymous-dev
anonymous-dev

Reputation: 3519

Laravel - Can I pass a parameter with apiResource to the index function in the controller?

Is there a way to pass a parameter into an apiResource route? I want only the index to take an userId. Adding {id} to the route does not seem to help. I looked at the laravel website but couldn't find anything about adding custom parameters.

I had a previous post about this but to make the question more clear I made a new post. I'll delete the previous post later today.

https://laravel.com/docs/5.7/controllers#resource-controllers

Route::apiResource('campaigns', 'CampaignController');

Upvotes: 2

Views: 2955

Answers (2)

francisco
francisco

Reputation: 2129

The index don't have an {id} by default.

If you want in laravel 8 change the naming of route parameters in apiResource just use parameters like:

Route::apiResource('users', AdminUserController::class)->parameters([
    'users' => 'id'
]);

This will generate these routes:

| POST      | api/users | users.store | App\Http\Controllers\AdminUserController@store 
| GET|HEAD  | api/users | users.index| App\Http\Controllers\AdminUserController@index
| GET|HEAD  | api/users/{id} | users.show   | App\Http\Controllers\AdminUserController@show 
| DELETE    | api/users/{id} | users.destroy| App\Http\Controllers\AdminUserController@destroy
| PUT|PATCH | api/users/{id} | users.update | App\Http\Controllers\AdminUserController@update 

Upvotes: 1

Alex Guerrero
Alex Guerrero

Reputation: 229

No theres no way to do thats but you can make this, and is the same.

Route::apiResource('campaigns', 'CampaignController',['except' => 'index']);

Route::get('campaigns/{id}', [
 'as' => 'campaigns.index',
 'uses' => 'CampaignController@index'
]);

Upvotes: 5

Related Questions