亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Introduction
Why Laravel and React?
Prerequisites
Installing and Setting Up Your Laravel Project
Validation and Exception Handling
Summary
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

Mar 01, 2025 am 09:14 AM

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles