RESTful API using LaravelAMVC Architecture

Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API

Laravel and React are two popular web development technologies used for building modern web applications. Laravel is prominently a server-side PHP framework, whereas React is a client-side JavaScript library. This tutorial serves as an introduction to both Laravel and React, combining them to create a modern web application. 

In a modern web application, the server has a limited job of managing the back end through some API (Application Programming Interface) endpoints. The client sends requests to these endpoints, and the server returns a response. However, the server is not concerned about how the client renders the view, which falls perfectly in line with the Separation of Concerns principle. This architecture allows developers to build robust applications for the web and also for different devices. 

In this tutorial, we will be using the latest version of Laravel, version 5.5, to create a RESTful back-end API. The front end will comprise of components written in React. We will be building a resourceful product listing application. The first part of the tutorial will focus more on the Laravel concepts and the back end. Let’s get started. 

Introduction

Laravel is a PHP framework developed for the modern web. It has an expressive syntax that favors the convention over configuration paradigm. Laravel has all the features that you need to get started with a project right out of the box. But personally, I like Laravel because it turns development with PHP into an entirely different experience and workflow.  

On the other hand, React is a popular JavaScript library developed by Facebook for building single-page applications. React helps you break down your view into components where each component describes a part of the application’s UI. The component-based approach has the added benefit of component reusability and modularity.

Why Laravel and React?

If you’re developing for the web, you might be inclined to use a single codebase for both the server and client. However, not every company gives the developer the freedom to use a technology of their choice, and for some good reasons. Using a JavaScript stack for an entire project is the current norm, but there’s nothing stopping you from choosing two different technologies for the server side and the client side. 

So how well do Laravel and React fit together? Pretty well, in fact. Although Laravel has documented supported for Vue.js, which is another JavaScript framework, we will be using React for the front-end because it’s more popular.

Prerequisites

Before getting started, I am going to assume that you have a basic understanding of the RESTful architecture and how API endpoints work. Also, if you have prior experience in either React or Laravel, you’ll be able to make the most out of this tutorial. 

However, if you are new to both the frameworks, worry not. The tutorial is written from a beginner’s perspective, and you should be able to catch up without much trouble. You can find the source code for the tutorial over at GitHub.

Installing and Setting Up Your Laravel Project

Laravel uses Composer to manage all the dependencies. So, before getting started with Laravel, download and install Composer on your machine. You might also need to configure the path environment variable so that Composer is accessible globally.

Run the following command to download the laravel installer.

If you’ve correctly configured the $PATH variable and added ~/.composer/vendor/bin in your path, you should be able to generate a fresh Laravel project as follows:

Alternatively, you can use Composer to create a new project without the laravel installer.

If everything goes well, you should be able to serve your application on a development server at http://localhost:8000.

Note: Artisan is a command-line tool that you can’t live without while working with Laravel. Artisan accepts a large list of commands that let you generate code for your application. Run php artisan list to view all of the available artisan commands.

Configuring the Environment

Your application will have a .env file inside the root directory. All the environment-specific configuration information is declared here. Create a database for your application if you haven’t already, and add the database details into the .env file.

Understanding Models, Routes, and Controllers

Laravel is a framework that follows the Model-View-Controller (MVC) architecture. Broadly speaking, MVC helps you to separate the database queries (the Model) from the logic concerned with how the requests should be processed (the Controller) and how the layout should be rendered (the View). The image below demonstrates the working of a typical Laravel application. 

Overview of Laravels architecture for building RESTful API endpoints
Laravel’s architecture. The controller returns the response and hence the view layer is not required.

Since we are building an API using Laravel, we will limit our discussion to the Model and the Controller. We shall review our options for creating the View in the second part of this tutorial. 

The Router

When the server receives an HTTP request, Laravel tries to match it with a route registered inside any of the route files. All the route files are located inside the routes directory. routes/web.php hosts the route for the web interface, whereas routes/api.php hosts the route for the API. The routes registered in api.php will be prefixed with /api (as in localhost:3000/api). If you need to change this behavior, you should head to the RouteServiceProvider class in /app/Providers/RouteServiceProvider.php and make changes there. 

Since we are building a product-listing application, here are the endpoints for the API and the HTTP actions associated with those endpoints. 

  • GET /products/: Retrieve all products.
  • GET /product/{id}: Retrieve the product that matches the id.
  • POST /products: Create a new product and insert it into the database.
  • PUT /products/{id} : Update an existing product that matches the id.
  • DELETE /products/{id}: Delete the product with the given id.

Let’s get the terminology right. GET, POST, PUT and DELETE are the HTTP verbs (more popularly known as HTTP methods) essentially required for building a RESTful service. /products is the URI associated with the products resource. The HTTP methods request the server to perform the desired action on a given resource.

HTTP actions acting on the Product resource
GET, POST, PUT and DELETE are the commonly used REST actions

The router allows you to declare routes for a resource along with the HTTP methods that target that resource. Here is a sample routes file that returns some hard-coded data.

routes/api.php

If you want to verify that the routes are working as expected, you should use a tool like POSTMAN or curl.

The Product Model

The products resource needs a model that can interact with the database. Model is the layer that sits on top of the database, hiding away all the database-specific jargon. Laravel uses Eloquent ORM for modeling the database. 

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. 
— Laravel Docs

What about the database schema definition? Laravel’s migration takes care of that. Artisan has a migration command that lets you define your schema and incrementally update it at a later stage. Let’s create a model and a migration for the Product entity. 

Note: There are lots of Artisan commands out there, and it’s easy to get lost. So every artisan command includes a helper screen that displays additional information such as the options and arguments available. To get to the help page, the name of the command should be preceded with help. Run the following help command to see what the -m option stands for: $ php artisan help make:model.

Here’s the migration file generated.

database/migrations/timestamp_create_products_table.php

The up method is called while migrating new tables and columns into the database, whereas the down method is invoked while rolling back a migration. We’ve created a Schema for a table with three rows: id, created_at, and updated_at. The $table->timestamps() method is responsible for maintaining the created_at and updated_at columns. Let’s add a couple more lines to the schema definition.

We’ve updated the schema with four new columns. Laravel’s schema builder supports a variety of column types like string, text, integer, boolean, etc.

To execute the pending migrations, you have to run the following command:

By convention, Laravel assumes that the Product model is associated with the products table. However, if you need to associate the model with a custom table name, you can use the $table property to declare the name of the table. The model will then be associated with a table named custom_products.

But we will keep things simple and go with the convention. The Product model generated is located inside the app/ directory. Although the model class may seem empty, it comes equipped with various query builder methods that you can use to query the database. For instance, you can use Product::all() to retrieve all the products or Product::find(1) to retrieve a particular product with id 1. 

Laravel models have a built-in protection mechanism against mass assignment vulnerability. The fillable property is used to declare the attribute names that can be mass assigned safely. 

app/Product.php

The code above whitelists the title, description, price and availability attributes and treats them as mass assignable. We can now use the Product::create method to insert new rows into the products table. 

Database Seeding

Laravel lets you populate your development and production database with dummy data which you then can use to test your API endpoints. You can create a seed class by executing the following Artisan command.

The generated seeder files will be placed in the database/seeds directory.

To generate the dummy data, you could use something like str_random(10) that returns a random string. But if you need data that is close enough to the actual data, you should use something like the faker library. Faker is a third-party library that gets shipped with the Laravel framework for generating fake data.

database/seeds/ProductsTableSeeder.php

Execute the db:seed artisan command to populate the database. 

Let’s head back to routes/api.php and fill in the missing pieces.

routes/api.php

The Controller

The route file currently hosts the logic for routing and handling requests. We can move the request handling logic to a Controller class so that our code is better organized and more readable. Let’s generate a controller class first.

The Controller class comprises of various methods (index, show, store, update, and delete) that correspond to different HTTP actions. I’ve moved the request handling logic from the route to the controller.

app/HTTP/Controllers/ProductsController.php

routes/api.php

If you haven’t noticed, I’ve injected an instance of Product into the controller methods. This is an example of Laravel’s implicit binding. Laravel tries to match the model instance name Product $product with the URI segment name {product}. If a match is found, an instance of the Product model is injected into the controller actions. If the database doesn’t have a product, it returns a 404 error. The end result is the same as before but with less code.

Open up POSTMAN and the endpoints for the product should be working. Make sure you have the Accept : application/json header enabled. 

Validation and Exception Handling

If you head over to a nonexistent resource, this is what you’ll see. 

The error page displayed for the NotFoundHTTPException

The NotFoundHTTPException is how Laravel displays the 404 error. If you want the server to return a JSON response instead, you will have to change the default exception handling behavior. Laravel has a Handler class dedicated to exception handling located at app/Exceptions/Handler.php. The class primarily has two methods: report() and render(). The report method is useful for reporting and logging exception events, whereas the render method is used to return a response when an exception is encountered. Update the render method to return a JSON response:

app/Exceptions/Handler.php

Laravel also allows us to validate the incoming HTTP requests using a set of validation rules and automatically return a JSON response if validation failed. The logic for the validation will be placed inside the controller. The IlluminateHttpRequest object provides a validate method which we can use to define the validation rules. Let’s add a few validation checks to the store method.

app/HTTP/Controllers/ProductsController.php

Summary

We now have a working API for a product listing application. However, the API lacks basic features such as authentication and restricting access to unauthorized users. Laravel has out-of-the-box support for authentication, and building an API for it is relatively easy. I encourage you to implement the authentication API as an exercise. 

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

Now that we’re done with the back end, we will shift our focus to the front-end concepts. Stay tuned for the second part of the series. Share your thoughts in the comments.

Powered by WPeMatico

Leave a Comment

Scroll to Top