Creating REST API in Laravel Part II (database, routes, controller, model)

In the previous article, we discuss about api and structure of response based on processing of client request. In this article, we will create database structure, model, resource routes and controller. As we have previously mentioned, we will use article as our entity for all of these processes.

Database Structure

We will create a migration to create articles table with following command.

See more details about migrations in official laravel documentation.

php artisan make:migration create_articles_table --create=articles

Above command will generate a database migration schema at app/database/migrations/ directory. We can see following structure in our migration file.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

When we execute php artisan migrate command, up function will run which creates articles table. Similarly, when we execute php artisan migrate:rollbackcommand, down function will run which removes article table from database.

Now, we will add title and body column to articles table. Then, our migration structure looks like:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

Now, we have to run following command to create articles table.

php artisan migrate
 

Hence we have created articles table in the database. Now, we will create eloquent model for the articles using following command.

php artisan make:model Article
 

Above console command will create Article model inside app/ directory which will look like,

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    //
}

See more details about eloquent model in laravel official documentation

Resource Routes and Controller for Restful Api

We can take reference of this article to create resource routes and controller.

Controller

Let's create an article controller with resource option with following command

php artisan make:controller ArticleController -r
 

Above command will generate ArticleControllerinside app/Http/Controllers. Later, we will make changes and add some logics to create rest api. The Article Controller looks something like this initially.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Since we are dealing only with api, so we don't need create and edit functions. later we will remove those functions. Now, we will create resource routes for pointing each of these functions.

Routes

Let's create resource route for article by adding following code to route/api.php file.

Route::resource('articles','ArticleController');
 

Above code will create following routes with prefix of api in each route.

Since, we don't need create and edit routes we can specify routes in following way.

Route::resource('articles','ArticleController',['except'=>['create','edit']]);
 

Hence, we have created database structure, routes and controller functions for creating api in laravel.

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api

In the next article, we will create validation request class to validate request parameters.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback