


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

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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Alipay PHP...

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,
