Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Shokouh Dareshiri Avatar asked Feb 16 '19 09:02

Shokouh Dareshiri


2 Answers

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
like image 199
Emtiaz Zahid Avatar answered Sep 18 '22 06:09

Emtiaz Zahid


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');
like image 38
Pianistprogrammer Avatar answered Sep 21 '22 06:09

Pianistprogrammer