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.

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

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:

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

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

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

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

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.

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.

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

Api Routes for Article

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

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.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

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