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

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.

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.

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.

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

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. 

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.

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.

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.

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.

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.

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.

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.

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

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.

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 IlluminateSupportFacadesSchema;

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.

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

We can now use the Product::create method to insert new rows into the products table.

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:

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

Now when query the API endpoint, I get the following result:

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. The ProductsController we generated is found in app/Http/Controllers/ProductsController.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 or VS Code and the endpoints for the product should be working. Make sure you have the Accept : application/json header enabled.

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 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 in app/Http/Controllers/ProductsController.php.

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: