Create restful APIs using Laravel 5 with resourceful routes example
In this post we will give you information about Create restful APIs using Laravel 5 with resourceful routes example. Hear we will give you detail about Create restful APIs using Laravel 5 with resourceful routes exampleAnd how to use it also give you demo for it if it is necessary.
Create restful API using Laravel 5 with resourceful routes example
It was hard for me to create rest API before but Laravel have developed with rest API concept.
In this tutorial, i will tell you how to create rest API in Laravel with resourceful routes for create, read, update and delete records.
REST known as Representational State Transfer. A REST API basically define set of method which handle request of client and generate responses via HTTP protocol such as GET and POST.
Here i write a rest api in Laravel which return in response of JSON format.
You can create rest APIs in minutes with Laravel.
If you want to quickly create your first test API with Laravel then open your routes.php and paste this code to see the response of API.
- Route::get('sample-restful-apis',function()
- {
- returnarray(
- 1=>"onlinecode",
- 2=>"demo"
- );
- });
Route::get('sample-restful-apis', function()
{
return array(
1 => "onlinecode",
2 => "demo"
);
});
When you run your URL with above route in browser then you will see the response in JSON-encoded string.
Here is response of above route :
- {
- "1":"onlinecode",
- "2":"demo"
- }
{
"1": "onlinecode",
"2": "demo"
}
OK, let’s start to create resourceful route :
- Route::group(array('prefix'=>'api'),function(){
- Route::resource('restful-apis','APIController');
- });
Route::group(array('prefix' => 'api'), function() {
Route::resource('restful-apis','APIController');
});
Here i add prefix api for all restful api that means all routes for rest api will be written within group with prefix api.
Note : don’t forget to exclude all routes start with api in your /app/Http/Middleware/VerifyCsrfToken.php otherwise you will get error of TokenMismatchException you may also disable CSRF while working with cURL to post something.
- protected $except=[
- 'api/*'
- ];
protected $except = [
'api/*'
];
Now i will create a APIController.php where i will handle all request generated by resourceful routes.
- <?php
- namespace AppHttpControllers;
- use IlluminateHttpRequest;
- use AppHttpControllersController;
- use AppProduct;
- class APIController extends Controller
- {
- public functionindex(Request $request)
- {
- $products= Product::paginate(5);
- returnresponse(array(
- 'error'=> false,
- 'products'=>$products->toArray(),
- ),200);
- }
- public functionstore(Request $request)
- {
- Product::create($request->all());
- returnresponse(array(
- 'error'=> false,
- 'message'=>'Product created successfully',
- ),200);
- }
- public functionshow($id)
- {
- $product= Product::find($id);
- returnresponse(array(
- 'error'=> false,
- 'product'=>$product,
- ),200);
- }
- public functionupdate(Request $request,$id)
- {
- Product::find($id)->update($request->all());
- returnresponse(array(
- 'error'=> false,
- 'message'=>'Product updated successfully',
- ),200);
- }
- public functiondestroy($id)
- {
- Product::find($id)->delete();
- returnresponse(array(
- 'error'=> false,
- 'message'=>'Product deleted successfully',
- ),200);
- }
- }
- ?>
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppHttpControllersController;
use AppProduct;
class APIController extends Controller
{
public function index(Request $request)
{
$products = Product::paginate(5);
return response(array(
'error' => false,
'products' =>$products->toArray(),
),200);
}
public function store(Request $request)
{
Product::create($request->all());
return response(array(
'error' => false,
'message' =>'Product created successfully',
),200);
}
public function show($id)
{
$product = Product::find($id);
return response(array(
'error' => false,
'product' =>$product,
),200);
}
public function update(Request $request, $id)
{
Product::find($id)->update($request->all());
return response(array(
'error' => false,
'message' =>'Product updated successfully',
),200);
}
public function destroy($id)
{
Product::find($id)->delete();
return response(array(
'error' => false,
'message' =>'Product deleted successfully',
),200);
}
}
?>
Now create a Product model for products table.
- <?php
- namespace App;
- use IlluminateDatabaseEloquentModel;
- class Product extends Model
- {
- public $fillable=['name','details'];
- }
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Product extends Model
{
public $fillable = ['name','details'];
}
Now i will show you response of each controller methods.
Response of index method
In this method i fetch product list.
- {
- "error":false,
- "status":,
- "products":{
- "total":17,
- "per_page":5,
- "current_page":1,
- "last_page":4,
- "next_page_url":"http://localhost/blog/public/restful-apis?page=2",
- "prev_page_url":null,
- "from":1,
- "to":5,
- "data":[
- {
- "id":1,
- "name":"product1",
- "details":"details of product1",
- "created_at":"2016-06-27 10:51:30",
- "updated_at":"2016-06-28 12:15:04"
- },
- {
- "id":2,
- "name":"onlinecode",
- "details":"onlinecode is a educational portal.",
- "created_at":"2016-06-24 10:53:57",
- "updated_at":"2016-06-24 10:54:48"
- },
- {
- "id":7,
- "name":"Laravel Restful APIs",
- "details":"Expertise in Laravel",
- "created_at":"2016-06-24 11:20:32",
- "updated_at":"2016-06-28 12:15:37"
- },
- {
- "id":8,
- "name":"product",
- "details":"demo product",
- "created_at":"2016-06-27 10:51:30",
- "updated_at":"2016-06-28 12:15:55"
- },
- {
- "id":11,
- "name":"CSRF",
- "details":"CSRF",
- "created_at":"2016-06-27 10:51:30",
- "updated_at":"2016-06-27 10:51:30"
- }
- ]
- }
- }
{
"error": false,
"status": 0,
"products": {
"total": 17,
"per_page": 5,
"current_page": 1,
"last_page": 4,
"next_page_url": "http://localhost/blog/public/restful-apis?page=2",
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
{
"id": 1,
"name": "product1",
"details": "details of product1",
"created_at": "2016-06-27 10:51:30",
"updated_at": "2016-06-28 12:15:04"
},
{
"id": 2,
"name": "onlinecode",
"details": "onlinecode is a educational portal.",
"created_at": "2016-06-24 10:53:57",
"updated_at": "2016-06-24 10:54:48"
},
{
"id": 7,
"name": "Laravel Restful APIs",
"details": "Expertise in Laravel",
"created_at": "2016-06-24 11:20:32",
"updated_at": "2016-06-28 12:15:37"
},
{
"id": 8,
"name": "product",
"details": "demo product",
"created_at": "2016-06-27 10:51:30",
"updated_at": "2016-06-28 12:15:55"
},
{
"id": 11,
"name": "CSRF",
"details": "CSRF",
"created_at": "2016-06-27 10:51:30",
"updated_at": "2016-06-27 10:51:30"
}
]
}
}
Response of store method
In this method i create new product.
- {"error":false,"message":"Product created successfully"}
{"error":false,"message":"Product created successfully"}
Response of show method
In this method i can see the particular product details.
- {
- "error":false,
- "product":{
- "id":1,
- "name":"product1",
- "details":"details of product1",
- "created_at":"2016-06-27 10:51:30",
- "updated_at":"2016-06-28 12:15:04"
- }
- }
{
"error": false,
"product": {
"id": 1,
"name": "product1",
"details": "details of product1",
"created_at": "2016-06-27 10:51:30",
"updated_at": "2016-06-28 12:15:04"
}
}
Response of update method
In this method i update product details.
- {"error":false,"message":"Product updated successfully"}
{"error":false,"message":"Product updated successfully"}
Response of destroy method
In this method i delete the product.
- {"error":false,"message":"Product deleted successfully"}
{"error":false,"message":"Product deleted successfully"}
Now you can create easily restful API in Laravel by following above code. You can also authentication your routes with unique token which you will get after login. Token will generate each time after login in application. Mobile application always prefer REST API.
Hope this code and post will helped you for implement Create restful APIs using Laravel 5 with resourceful routes example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs