Google+
Shineyrock web design & consultancy

Shineyrock

blog

  • dislike -4 22

    Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 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 9, to create a RESTful back-end API. The front end will comprise 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 support 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

    Before getting started with Laravel, make sure you have installed both PHP and Composer on your local machine. This is because Laravel is based on PHP and uses Composer to manage all the dependencies. When installing Composer on your machine, ensure that you choose the option for adding it to the path environment variable so that Composer is accessible globally. 

    Once Composer has been installed, you should be able to generate a fresh Laravel project as follows:

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

    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. 

    Here we are connecting a database named sampledb to the application. This database is hosted on MySQL, which is running locally (i.e. http://127.0.0.1) at port 3306. The database username is root, and the password is empty. This is the default username and password for MySQL databases.

    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.

    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.

    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. Ensure that the development server is running before querying the API endpoints. For example, here's the response I got from querying the http://127.0.0.1:8000/api/products/1/ API endpoint using the REST client in Visual Studio Code:

    ScreenshotScreenshotScreenshot
    Screenshot of API response

    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.

    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 in 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, and boolean.

    The Product Model

    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.

    This code should be in app/Models/Product.php:

    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.

    The code above whitelists the title, description, price and availability attributes and treats them as mass assignable.

    Finally, run the following command to execute the pending migrations.

    If running this command gives you a "Syntax error or access violation" error, go into app/Providers/AppServiceProvider.php and include Schema::defaultStringLength(191); in the boot() method. Make sure you import the Schema class at the file top with use Illuminate\Support\Facades\Schema;

    This command will create the default tables (e.g. users, migrations) and the table you defined (products) inside the sampledb database which we earlier set as the application database in the .env file.

    Tables in sampledbTables in sampledbTables in sampledb
    Tables in sampledb

    The products table also has the fields and schema which we defined for it in the migration file.

    Products table structureProducts table structureProducts table structure
    Products table structure

    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/seeders 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.

    Here is a seeder class for generating seed data. It should go in database/seeders/ProductsTableSeeder.php.

    Execute the db:seed artisan command to populate the products table with fake data.

    Here's the result:

    Table populated with fake dataTable populated with fake dataTable populated with fake data
    Table populated with fake data

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

    Now, when we query the http://127.0.0.1:8000/api/products/1/ API endpoint, we get the following result:

    API responseAPI responseAPI response
    API response

    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 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. The ProductsController we generated is found in app/Http/Controllers/ProductsController.php.

    Now update routes/api.php with the new import and routes.

    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 or VS Code 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 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:

    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 Illuminate\Http\Request 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 in 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.

    Now that we're done with the back end, we will shift our focus to the front-end concepts. Check out the second post in this series here:

    martijn broeders

    founder/ strategic creative at shineyrock web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    phone: 434 210 0245

By - category

    By - date