Published on August 14, 2024By DeveloperBreeze

Title: Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

Introduction

Combining Laravel’s powerful backend capabilities with React’s dynamic frontend framework allows you to build robust full-stack web applications. With Vite serving as the build tool, you can efficiently manage your frontend assets while taking advantage of Laravel's capabilities for database management, routing, and API development. In this tutorial, we’ll guide you through setting up a Laravel project with React using Vite, and demonstrate how to use databases and PHP code within this setup.

Prerequisites

  • Basic understanding of Laravel, React, and JavaScript.

  • Familiarity with npm or Yarn.

  • A Laravel project set up on your local machine.

Step 1: Setting Up Laravel for Database Operations

Laravel provides a built-in ORM (Object-Relational Mapping) called Eloquent, which simplifies database interactions. Let's start by configuring the database and creating the necessary models and migrations.

1.1 Configure the Database

First, open your .env file and configure the database connection settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

Replace the placeholders with your actual database details.

1.2 Create a Migration

Migrations in Laravel allow you to define and modify your database schema. Let's create a migration for a posts table:

php artisan make:migration create_posts_table

In the generated migration file (database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php), define the schema:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

1.3 Create a Model

Next, create an Eloquent model that represents the posts table:

php artisan make:model Post

In the Post model (app/Models/Post.php), define the fields that can be mass assigned:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'body'];
}

Step 2: Creating API Endpoints with Laravel

React will interact with Laravel’s backend through API endpoints. We'll create a controller and define routes for CRUD operations.

2.1 Create a Controller

Generate a controller to handle the logic for your Post model:

php artisan make:controller PostController

In the PostController (app/Http/Controllers/PostController.php), define methods to manage posts:

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        return Post::all();
    }

    public function store(Request $request)
    {
        $post = Post::create($request->all());
        return response()->json($post, 201);
    }

    public function show($id)
    {
        return Post::findOrFail($id);
    }

    public function update(Request $request, $id)
    {
        $post = Post::findOrFail($id);
        $post->update($request->all());
        return response()->json($post, 200);
    }

    public function destroy($id)
    {
        Post::destroy($id);
        return response()->json(null, 204);
    }
}

2.2 Define API Routes

In routes/api.php, define routes that correspond to the controller methods:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
Route::post('/posts', [PostController::class, 'store']);
Route::put('/posts/{id}', [PostController::class, 'update']);
Route::delete('/posts/{id}', [PostController::class, 'destroy']);

These routes handle listing, creating, viewing, updating, and deleting posts.

Step 3: Integrating React with Laravel

Now that the backend is ready, we’ll integrate React to consume these API endpoints and build the frontend.

3.1 Setting Up Vite for React

Ensure that Vite is configured to handle React in your project:

    • Install React and React DOM:

npm install react react-dom
   

    • Modify Vite Configuration:

In vite.config.js, set up Vite to work with React:

import { defineConfig } from 'vite';
   import laravel from 'laravel-vite-plugin';
   import react from '@vitejs/plugin-react';

   export default defineConfig({
       plugins: [
           laravel({
               input: ['resources/css/app.css', 'resources/js/app.jsx'],
               refresh: true,
           }),
           react(),
       ],
   });
   

    • Create the Entry Point:

Rename resources/js/app.js to app.jsx and set up a basic React component:

import React from 'react';
   import ReactDOM from 'react-dom/client';

   function App() {
       return (
           <div>
               <h1>Hello, React in Laravel with Vite!</h1>
           </div>
       );
   }

   const rootElement = document.getElementById('app');
   if (rootElement) {
       const root = ReactDOM.createRoot(rootElement);
       root.render(<App />);
   }
   

3.2 Consuming the API in React

Let’s create a React component that interacts with the Laravel API to display and manage posts.

    • Fetching Data:

Use axios or fetch to retrieve posts from the API:

import React, { useState, useEffect } from 'react';
   import axios from 'axios';

   function Posts() {
       const [posts, setPosts] = useState([]);

       useEffect(() => {
           axios.get('/api/posts')
               .then(response => {
                   setPosts(response.data);
               })
               .catch(error => {
                   console.error('There was an error fetching the posts!', error);
               });
       }, []);

       return (
           <div>
               <h1>Posts</h1>
               <ul>
                   {posts.map(post => (
                       <li key={post.id}>{post.title}</li>
                   ))}
               </ul>
           </div>
       );
   }

   export default Posts;
   

    • Submitting Data:

Create a form in React to submit new posts:

function CreatePost() {
       const [title, setTitle] = useState('');
       const [body, setBody] = useState('');

       const handleSubmit = (event) => {
           event.preventDefault();

           axios.post('/api/posts', { title, body })
               .then(response => {
                   console.log('Post created:', response.data);
               })
               .catch(error => {
                   console.error('There was an error creating the post!', error);
               });
       };

       return (
           <form onSubmit={handleSubmit}>
               <div>
                   <label>Title:</label>
                   <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
               </div>
               <div>
                   <label>Body:</label>
                   <textarea value={body} onChange={(e) => setBody(e.target.value)}></textarea>
               </div>
               <button type="submit">Create Post</button>
           </form>
       );
   }

   export default CreatePost;
   

Step 4: Handling Authentication and Middleware

For applications requiring authentication, Laravel offers built-in tools like Sanctum or Jetstream. You can protect API routes and access them from React using tokens or cookies.

4.1 Protecting Routes with Middleware

To protect API routes, use Laravel’s middleware:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

4.2 Using Laravel Sanctum for API Authentication

Laravel Sanctum provides a simple token-based API authentication system. Once set up, you can authenticate API requests from React using Bearer tokens.

Step 5: Deploying the Laravel + React Project

When you’re ready to deploy your application:

    • Build the React App:

Build the frontend assets for production:

npm run build
   

Or with Yarn:

yarn build
   

    • Serve Compiled Assets:

Laravel will automatically serve the compiled assets in production, ensuring your application is optimized and ready for users.

Conclusion

By following this tutorial, you’ve successfully integrated Laravel and React using Vite. You learned how to set up database operations in Laravel, create API endpoints, and build a React frontend that interacts with Laravel’s backend. This setup is ideal for modern full-stack web development, allowing you to leverage Laravel’s powerful backend features with React’s dynamic frontend capabilities.

Comments

Please log in to leave a comment.

Continue Reading:

Generate Random Password

Published on January 26, 2024

javascriptpythonphp

Various cURL Examples for API Interactions

Published on January 26, 2024

bash

Upload and Store File in Laravel

Published on January 26, 2024

php

Create Event and Listener in Laravel

Published on January 26, 2024

bash

Querying Data from Database Table in Laravel

Published on January 26, 2024

php

Laravel CSRF-Protected Form

Published on January 26, 2024

html

Create Resource Controller in Laravel

Published on January 26, 2024

bash

Laravel Validation Rules for User Registration

Published on January 26, 2024

php

Blade View in Laravel Extending Layout

Published on January 26, 2024

html