Create Rest API in Laravel 5.8

In this tutorial, we are going to see how we can create REST API in Laravel 5.8. Before jump to steps of this tutorial we need to install laravel and configure database. Once we done with Laravel installation and Database Configuration we are good to go with below steps to create REST API.

Step 1 : Create a migration file for posts table

 php artisan make:migration create_posts_table

Migration file would like like as below

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('alias')->unique();
        $table->text('content');
        $table->timestamps();
    });
}

Step 2 : Create Model

php artisan make:model Post

Our Post models will be placed in app directory. (app/Post.php)

Step 3: Create Seeder

php artisan make:seeder PostsTableSeeder

Update the run() method in PostsTableSeeder as below. Manually specifying the data for test in posts table is cumbersome. So we have used factory to generate fake data inside our posts table.

public function run()
{
    factory(App\Post::class, 100)->create();
}

Remeber to update your DatabaseSeeder.php in seeds directory. This takes our newly created PostsTableSeeder.php file to seed the data in posts table.

public function run()
{
    $this->call(PostsTableSeeder::class);
}

Step 3: Generate Factory and seed data

php artisan make:factory PostFactory --model=Post

The new factory will be placed in your database/factories directory.

<?php

use Faker\Generator as Faker;

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        //
    	'title' => $faker->text(50),
    	'alias' => $faker->slug(20),
        'content'  => $faker->text(200)
    ];
});
php artisan db:seed

Step 4 : Create API Resource Routes

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::apiResource('posts', 'API\PostController');

//This one line of code will automatically generate following REST api routes for us
//Route::get('posts', 'API\PostController@index');
//Route::post('posts', 'API\PostController@store');
//Route::get('posts/{id}', 'API\PostController@show');
//Route::put('posts/{id}', 'API\PostController@update');
//Route::delete('posts/{id}', 'API\PostController@destroy');

Step 5 : Create API Resource Controller

php artisan make:controller API/PostController --api

After creating PostController under API directory now its time to review our PostController. Default Laravel generate all the methods for REST API in our controller. We need to change this controller as per our requirement. Here you can find updated controller for basic Create, Read, Update and Delete operation on our Post Model and response will be generated as we defined in our PostResource (app\Http\Resources\Post.php) file.

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;

use App\Http\Resources\Post as PostResource;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $posts = Post::get();
        
        return PostResource::collection($posts);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $post = new Post;
        $post->title = $request->title;
        $post->alias = $request->alias;
        $post->content = $request->content;
        $post->save();

        return new PostResource($post);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $post = Post::findOrFail($id);

        return new PostResource($post);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $post = Post::findOrFail($id);

        $post->title = $request->title;
        $post->alias = $request->alias;
        $post->content = $request->content;
        $post->save();

        return new PostResource($post);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $post = Post::findOrFail($id);

        $post->delete();

        return new PostResource($post);
    }
}

After starting the local server if your web server runs on 8000 port then your URLs would be like as below. Post 8000 might change for your system.

Request
OperationUrl
GETList all Postshttp://127.0.0.1:8000/api/posts
POSTCreate a New Posthttp://127.0.0.1:8000/api/posts
GETRead a Single Posthttp://127.0.0.1:8000/api/posts/{postId}
PUTUpdate a Single Posthttp://127.0.0.1:8000/api/posts/{postId}
DELETEDelete a Single Posthttp://127.0.0.1:8000/api/posts/{postId}

You can download the code from github

https://github.com/hectacode/rest-api-in-laravel5.8

Leave a Reply

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