Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 956

Laravel Route apiResource (difference between apiResource and resource in route)

I'm using apiResource in Route which is using (index, create, show, update, destroy) methods in exampleController. When I would like to use show method the route wont work. what shall I do? I think it is because of {fruits} but I do not how solve it?

Route::apiResource('/fruit/{fruits}/apples', 'exampleController');

My route in browser is:

localhost:8000/api/fruits/testFruitSlug/apples/testAppleSlug

difference between apiResource and resource in route: Route::apiResource() only creates routes for index, store, show, update and destroy while Route::resource() also adds a create and edit route which don't make sense in an API context.

Upvotes: 32

Views: 65713

Answers (3)

Emtiaz Zahid
Emtiaz Zahid

Reputation: 2855

Already peoples added answers, I am just adding the route differences as visually :

Normal Resource controller

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

Api Resource controller

Route::apiResource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

Upvotes: 58

Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 956

I solved my question in below way:

public function show(Fruits $fruits, Apples $apples){

}

I found that I should give all variables in my function however I did not use all of them.

Upvotes: 0

Pianistprogrammer
Pianistprogrammer

Reputation: 637

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/PhotoController --api

Try using the command line to generate your controller. It will save you stress. You can then do this in your route

Route::apiResource('photos', 'PhotoController');

Upvotes: 24

Related Questions