How to create REST API in Laravel 5 ?

How to create REST API in Laravel 5 ?

In this post we will give you information about How to create REST API in Laravel 5 ?. Hear we will give you detail about How to create REST API in Laravel 5 ?And how to use it also give you demo for it if it is necessary.

In this tutorial, i would like to share with you how to build restful api in laravel 5.5 application. Here i will share with you create basic and simple resource api route with json response. you can simply use with your big project, you can make basic setup for you application.

Before start i would like to recommend following link for authentication api : Laravel 5 – How to create API Authentication using Passport ?. Here i explained how to create api authentication, so you can make authentication apis with posts restful api.

In this example i will create posts table and create rest api of posts with resource route. Here i also attach screen shot for all resource route response, so you can check response for GET, POST, PUT and DELETE for list, create, update and delete. So let’s just follow bellow step and you will get best api platform.

Here is Routes URL with Verb:

1) List: Verb:GET, URL:http://localhost:8000/api/posts

2) Create: Verb:POST, URL:http://localhost:8000/api/posts

3) Show: Verb:GET, URL:http://localhost:8000/api/posts/{id}

4) Update: Verb:PUT, URL:http://localhost:8000/api/posts/{id}

5) Delete: Verb:DELETE, URL:http://localhost:8000/api/posts/{id}

Step 1 : Install Laravel 5.5 App

we are going to from scratch so, we need to get fresh Laravel 5.5 application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Create Post Table and Model

next, we require to create migration for posts table using Laravel 5.5 php artisan command, so first fire bellow command:

php artisan make:migration create_posts_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create posts table.

<?php


use IlluminateSupportFacadesSchema;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateDatabaseMigrationsMigration;


class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('description');

$table->timestamps();

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

After create “posts” table you should create Item model for posts, so first create file in this path app/Post.php and put bellow content in item.php file:

app/Post.php

<?php


namespace App;


use IlluminateDatabaseEloquentModel;


class Post extends Model

{


protected $fillable = [

'name', 'description',

];

}

Also see:How to create and check custom header with middleware for REST API in Laravel 5 ?

Step 3: Create Rest API Route

In this is step we should create resource routes for list, create, update and delete. so open your routes/api.php file and add following route.

routes/api.php

Route::resource('posts', 'APIPostAPIController');


Step 4: Create Controllers

in next step, now we have create new controller as APIBaseController and PostAPIController, i created new folder “API” in Controllers folder because we will make alone APIs controller, So let’s create both controller:

app/Http/Controllers/API/APIBaseController.php

<?php


namespace AppHttpControllersAPI;


use IlluminateHttpRequest;

use AppHttpControllersController as Controller;


class APIBaseController extends Controller

{


public function sendResponse($result, $message)

{

$response = [

'success' => true,

'data' => $result,

'message' => $message,

];


return response()->json($response, 200);

}


public function sendError($error, $errorMessages = [], $code = 404)

{

$response = [

'success' => false,

'message' => $error,

];


if(!empty($errorMessages)){

$response['data'] = $errorMessages;

}


return response()->json($response, $code);

}

}

app/Http/Controllers/API/PostAPIController.php

Also see:Laravel 5.5 CRUD Example from scratch

<?php


namespace AppHttpControllersAPI;


use IlluminateHttpRequest;

use AppHttpControllersAPIAPIBaseController as APIBaseController;

use AppPost;

use Validator;


class PostAPIController extends APIBaseController

{

/**

* Display a listing of the resource.

*

* @return IlluminateHttpResponse

*/

public function index()

{

$posts = Post::all();

return $this->sendResponse($posts->toArray(), 'Posts retrieved successfully.');

}


/**

* Store a newly created resource in storage.

*

* @param IlluminateHttpRequest $request

* @return IlluminateHttpResponse

*/

public function store(Request $request)

{

$input = $request->all();


$validator = Validator::make($input, [

'name' => 'required',

'description' => 'required'

]);


if($validator->fails()){

return $this->sendError('Validation Error.', $validator->errors());

}


$post = Post::create($input);


return $this->sendResponse($post->toArray(), 'Post created successfully.');

}


/**

* Display the specified resource.

*

* @param int $id

* @return IlluminateHttpResponse

*/

public function show($id)

{

$post = Post::find($id);


if (is_null($post)) {

return $this->sendError('Post not found.');

}


return $this->sendResponse($post->toArray(), 'Post retrieved successfully.');

}


/**

* Update the specified resource in storage.

*

* @param IlluminateHttpRequest $request

* @param int $id

* @return IlluminateHttpResponse

*/

public function update(Request $request, $id)

{

$input = $request->all();


$validator = Validator::make($input, [

'name' => 'required',

'description' => 'required'

]);


if($validator->fails()){

return $this->sendError('Validation Error.', $validator->errors());

}


$post = Post::find($id);

if (is_null($post)) {

return $this->sendError('Post not found.');

}


$post->name = $input['name'];

$post->description = $input['description'];

$post->save();


return $this->sendResponse($post->toArray(), 'Post updated successfully.');

}


/**

* Remove the specified resource from storage.

*

* @param int $id

* @return IlluminateHttpResponse

*/

public function destroy($id)

{

$post = Post::find($id);


if (is_null($post)) {

return $this->sendError('Post not found.');

}


$post->delete();


return $this->sendResponse($id, 'Tag deleted successfully.');

}

}

Now simply you can run above listed url like as bellow screen shot:

Post List API:

Post Create API:

Post Show API:

Post Update API:

Post Delete API:

I hope it can help you…

Hope this code and post will helped you for implement How to create REST API in Laravel 5 ?. 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

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

88  +    =  96

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US