Home >Backend Development >PHP Tutorial >Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API

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

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-03-01 09:14:10486browse

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:

composer create-project laravel/laravel example-app<br>

If everything goes well, you should be able to serve your application on a development server at ProductsController we generated is found in app/Http/Controllers/ProductsController.php.

<?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Product;<br><br>class ProductsController extends Controller<br>{<br><br>    public function index()<br>	{<br>	    return Product::all();<br>	}<br><br>	public function show(Product $product)<br>	{<br>	    return $product;<br>	}<br><br>	public function store(Request $request)<br>	{<br>	    $product = Product::create($request->all());<br><br>	    return response()->json($product, 201);<br>	}<br><br>	public function update(Request $request, Product $product)<br>	{<br>	    $product->update($request->all());<br><br>	    return response()->json($product, 200);<br>	}<br><br>	public function delete(Product $product)<br>	{<br>	    $product->delete();<br><br>	    return response()->json(null, 204);<br>	}<br><br>}<br>
Now update routes/api.php with the new import and routes.
// Include this at the file top:<br>use App\Http\Controllers\ProductsController;<br><br>/**<br>**Basic Routes for a RESTful service:<br>**Route::get($uri, $callback);<br>**Route::post($uri, $callback);<br>**Route::put($uri, $callback);<br>**Route::delete($uri, $callback);<br>**<br>*/<br><br><br>Route::get('products', 'ProductsController@index');<br><br>Route::get('products/{product}', 'ProductsController@show');<br><br>Route::post('products','ProductsController@store');<br><br>Route::put('products/{product}','ProductsController@update');<br><br>Route::delete('products/{product}', 'ProductsController@delete');<br><br><br>

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<code>Product $product with the URI segment name {product}<code>{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<code>Accept : application/json header enabled.

Validation and Exception Handling

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

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

The NotFoundHTTPException<code>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()<code>report() and render()<code>render(). The report<code>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:

composer create-project laravel/laravel example-app<br>

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.

<?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Product;<br><br>class ProductsController extends Controller<br>{<br><br>    public function index()<br>	{<br>	    return Product::all();<br>	}<br><br>	public function show(Product $product)<br>	{<br>	    return $product;<br>	}<br><br>	public function store(Request $request)<br>	{<br>	    $product = Product::create($request->all());<br><br>	    return response()->json($product, 201);<br>	}<br><br>	public function update(Request $request, Product $product)<br>	{<br>	    $product->update($request->all());<br><br>	    return response()->json($product, 200);<br>	}<br><br>	public function delete(Product $product)<br>	{<br>	    $product->delete();<br><br>	    return response()->json(null, 204);<br>	}<br><br>}<br>

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:

The above is the detailed content of Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Learn LaravelNext article:Learn Laravel