Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Resourceful API Controller In PHP Laravel


Simple Way To Create Resourceful API Controller In Laravel


Share On     Share On WhatsApp     Share On LinkedIn


Hello There! I am back with another article on in my previous article I had shown you how to create Resourceful Controller for web in What Is Laravel Resourceful Controllers? article.


In this article I will show you how to


  1. Command To Create Simple Resourceful API Controllers
  2. Model Specific Resourceful API Controllers
  3. Automatic Routes Inside api.php
  4. Manual Routes Inside api.php
  5. Controllers Tricks For REST API

Prerequisites


Laravel installed in your computer or server. To install Laravel you can use the following


composer create-project --prefer-dist laravel/laravel invoice

1) Command To Create Simple Resourceful API Controllers


Since I already had ProductsController for web.php demonstration I created ProductApiController for demonstrating the Resourceful API controller with routes inside api.php. And I am using Product as model name which resides inside App/Models/Product.php


php artisan make:controller ProductsApiController --api --resource


--resource - This parameter specifies that we are creating the resourceful controller.

--api - Specifies that we are creating API controller.


API resourceful controller creates the following functions inside ProductApiController


index()
store()
show()
update()
destroy()


Observe that it has not created


create()
edit()


As we are creating REST API Controller here we don't need any create() or edit() view pages.


2) Model Specific Resourceful API Controllers


Another beautiful thing what you can do with Laravel is specify the Model while creating the Resourceful API Controller because for Route Model Binding.


If you would like to learn more on route model binding then refer my article @ Route Model Binding In Laravel


php artisan make:controller ProductsApiController --api --resource --model Models/Product.php


--model - Since my Product.php model resides in App/Models/Product.php I have give the path as Models/Product.php. If you have model directly as App/Product.php then you can give --model Product.php


But as far as I know Route Model Binding with API's is bit tricky and sneaky one.


3) Automatic Routes Inside api.php


Instead of adding individual API routes in api.php file you can simply add the following code. This will create the routes automatically for us.


Route::apiResource('products', 'ProductsApiController');


You can also register multiple API routes at once with the following code


Route::apiResources([
    'photos' => 'ProductsController',
    'posts'  => 'InvoiceController'
]);


In the above line observer apiResource carefully. This will generate API routes only.


To check the list of available routes you can use the following command


php artisan route:list


You will be able to see similar to the following output. You will be able to see other fields along with the 3 columns I have actually filtered the columns with the following command


php artisan route:list --columns=Method,URI,Action


+-----------+-------------------------+----------------------------------------------------+
| Method    | URI                     | Action                                             |
+-----------+-------------------------+----------------------------------------------------+

| GET|HEAD  | api/products            | App\Http\Controllers\ProductsApiController@index   |

| POST      | api/products            | App\Http\Controllers\ProductsApiController@store   |

| GET|HEAD  | api/products/{product}  | App\Http\Controllers\ProductsApiController@show    |

| PUT|PATCH | api/products/{product}  | App\Http\Controllers\ProductsApiController@update  |

| DELETE    | api/products/{product}  | App\Http\Controllers\ProductsApiController@destroy |

4) Manual Routes Inside api.php


We saw how to add the automatic routes inside our api.php, just incase if you feel secured or want very few routes with few modifications then you can use the following way


api.php

Route::get('/products', 'ProductsApiController@index');
Route::post('/products', 'ProductsApiController@store');
Route::get('/products/{product}', 'ProductsApiController@show');
Route::patch('/products/{product}', 'ProductsApiController@update');
Route::delete('/products/{product}', 'ProductsApiController@destroy');


Even these routes can be access with api prefixed with it. as follows


http://your_domain.com/api/products
http://your_domain.com/api/products/product_id

5) Controllers Tips For REST API


Now lets have a look at our implementation part. Basically here I will show you some tips


Validation


Basically in REST validation you need to return the JSON response. You can use the following way to validate and return the JSON response.


use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'name'          => 'required',
    'product_image' => 'required',
]);
if ($validator->fails()) {
    return response()->json([
        'status' => 'error', 
        'errors' => $validator->errors()
    ], 400);
}


Observe the following from the above code. We are using Validator to check the validation. It takes 2 parameters 1st is the POST form details we get this in Request $request variable, 2nd parameter takes the rules to validate the form data.


Validator::make($request->all(), [
    'name'          => 'required',
    'product_image' => 'required',
]);

Returning JSON Response


We need to return if any validation fails. This needs to be in JSON response. Laravel provides simple way to achieve the same.


return response()->json(data_need_to_send, status_code);


1st Parameter (Data)- Usually the array of data that you need to send


2nd Parameter (Status Code) - This is the status code that needs to be sent if any success or errors


I basically use the following format for success


return response()->json([
    'status'    => 'success',
    'message'   => 'List of products.',
    'data'       => [
        'products'  => $product
    ]
], 200);


For errors I use the following format


return response()->json([
    'status'    => 'error',
    'message'   => $e->getMessage(),
    'errors'    => $errors /* Validation errors */
], 400);


Conclusion


Hope the article was very helpful for you. Please check the related article which might be very helpful for you.


WHATS NEXT?


What Is Laravel Resourceful Controllers?

What Is HTTP? Different HTTP Methods And Status Codes Explained With Examples


Happy Coding :)








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing