search
HomeBackend DevelopmentPHP TutorialBuild 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:

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.