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.
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
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:
composer create-project laravel/laravel example-app
If everything goes well, you should be able to serve your application on a development server at https://localhost:8000
.
php artisan serve
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.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=sampledb DB_USERNAME=root DB_PASSWORD=
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.
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 theid
. - POST
/products
: Create a new product and insert it into the database. - PUT
/products/{id}
: Update an existing product that matches theid
. - DELETE
/products/{id}
: Delete the product with the givenid
.
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.
routes/api.php
/** ** Basic Routes for a RESTful service: ** ** Route::get($uri, $callback); ** Route::post($uri, $callback); ** Route::put($uri, $callback); ** Route::delete($uri, $callback); ** **/ Route::get('products', function () { return response(['Product 1', 'Product 2', 'Product 3'],200); }); Route::get('products/{product}', function ($productId) { return response()->json(['productId' => "{$productId}"], 200); }); Route::post('products', function() { return response()->json([ 'message' => 'Create success' ], 201); }); Route::put('products/{product}', function() { return response()->json([ 'message' => 'Update success' ], 200); }); Route::delete('products/{product}',function() { return response()->json(null, 204); });
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:
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.
$ php artisan make:model Product -m
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:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } };
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.
/* Let's add columns for title, description, price, availability */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('title'); $table->text('description'); $table->integer('price'); $table->boolean('availability'); }); }
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:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; // Add this: protected $table = '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.
/* Add the fillable property into the Product Model */ protected $fillable = ['title', 'description', 'price', 'availability'];
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.
php artisan migrate
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.
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.
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.
$ php artisan make:seeder ProductsTableSeeder
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.
use App\Models\Product; class ProductsTableSeeder extends Seeder { public function run() { $faker = \Faker\Factory::create(); // Create 50 product records for ($i = 0; $i < 50; $i++) { Product::create([ 'title' => $faker->title, 'description' => $faker->paragraph, 'price' => $faker->randomNumber(2), 'availability' => $faker->boolean(50) ]); } } }
Execute the db:seed
artisan command to populate the products table with fake data.
$ php artisan db:seed --class=ProductsTableSeeder
Here’s the result:
Let’s head back to routes/api.php and fill in the missing pieces.
// Include this at the top of the file: use App\Models\Product; /** **Basic Routes for a RESTful service: **Route::get($uri, $callback); **Route::post($uri, $callback); **Route::put($uri, $callback); **Route::delete($uri, $callback); ** */ Route::get('products', function () { return response(Product::all(),200); }); Route::get('products/{product}', function ($productId) { return response(Product::find($productId), 200); }); Route::post('products', function(Request $request) { $resp = Product::create($request->all()); return $resp; }); Route::put('products/{product}', function(Request $request, $productId) { $product = Product::findOrFail($productId); $product->update($request->all()); return $product; }); Route::delete('products/{product}',function($productId) { Product::find($productId)->delete(); return 204; });
Now when query the http://127.0.0.1:8000/api/products/1/ API endpoint, I get the following result:
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.
$ php artisan make:controller ProductsController
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.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Product; class ProductsController extends Controller { public function index() { return Product::all(); } public function show(Product $product) { return $product; } public function store(Request $request) { $product = Product::create($request->all()); return response()->json($product, 201); } public function update(Request $request, Product $product) { $product->update($request->all()); return response()->json($product, 200); } public function delete(Product $product) { $product->delete(); return response()->json(null, 204); } }
Now update routes/api.php with the new import and routes.
// Include this at the file top: use App\Http\Controllers\ProductsController; /** **Basic Routes for a RESTful service: **Route::get($uri, $callback); **Route::post($uri, $callback); **Route::put($uri, $callback); **Route::delete($uri, $callback); ** */ Route::get('products', 'ProductsController@index'); Route::get('products/{product}', 'ProductsController@show'); Route::post('products','ProductsController@store'); Route::put('products/{product}','ProductsController@update'); Route::delete('products/{product}', 'ProductsController@delete');
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:
public function render($request, Exception $exception) { if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { return response()->json([ 'message' => 'Resource not found' ], 404); } return parent::render($request, $exception); }
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.
public function store(Request $request) { $this->validate($request, [ 'title' => 'required|unique:products|max:255', 'description' => 'required', 'price' => 'integer', 'availability' => 'boolean', ]); $product = Product::create($request->all()); return response()->json($product, 201); }
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: