DeveloperBreeze

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:

  1. Install React and React DOM:
   npm install react react-dom
  1. 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(),
       ],
   });
  1. 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.

  1. 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;
  1. 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:

  1. Build the React App:

Build the frontend assets for production:

   npm run build

Or with Yarn:

   yarn build
  1. 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.

Related Posts

More content you might like

Article

Mastering Modern Web Development: Trends, Tools, and Tutorials for 2025 and Beyond

  • Framework: Choose Next.js for its versatility.
  • Styling: Integrate Tailwind CSS for a responsive design.
  • Containerization: Install Docker to containerize your application for development and production.
  • Core Functionality: Develop a simple blog that fetches posts from an external API.
  • Enhancements: Integrate a micro frontend component (e.g., a comment widget) developed with React.
  • AI Integration: Add a recommendation engine using a third-party machine learning API to suggest related posts.

Feb 11, 2025
Read More
Tutorial
python

Build a Facial Recognition Attendance System

import sqlite3

# Connect to SQLite database
conn = sqlite3.connect("attendance.db")
cursor = conn.cursor()

# Create table
cursor.execute("""
    CREATE TABLE IF NOT EXISTS attendance (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
    )
""")

def log_attendance(name):
    cursor.execute("INSERT INTO attendance (name) VALUES (?)", (name,))
    conn.commit()

# Update the webcam loop to log attendance
if name not in attendance_log:
    attendance_log.add(name)
    log_attendance(name)
    print(f"{name} marked present in the database!")

Use schedule to automate the script to run at specific times (e.g., every morning):

Dec 10, 2024
Read More
Article

Integrating Flowbite with Tailwind CSS: A Step-by-Step Tutorial

  • Set Up: Initialized a Node.js project and installed Tailwind CSS.
  • Installed Flowbite: Added Flowbite to your project via npm.
  • Configured Tailwind: Updated Tailwind's configuration to include Flowbite's styles.
  • Built CSS: Compiled Tailwind and Flowbite styles into a single CSS file.
  • Implemented Components: Utilized Flowbite's components in your HTML.
  • Seamless Integration: Flowbite complements Tailwind CSS by offering a plethora of interactive components, enhancing the design and functionality of your web projects.
  • Customization: Both Tailwind CSS and Flowbite are highly customizable, allowing you to tailor components to match your design aesthetics precisely.
  • Efficiency: Leveraging pre-built components reduces development time, enabling you to focus on building unique features rather than reinventing UI elements.

Oct 24, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

Add the following code to your app.js file within the db.serialize() block, after the table creation:

// Insert data into the "accounts" table
const stmt = db.prepare('INSERT INTO accounts (private_key, address, decimalNumber, has_transactions) VALUES (?, ?, ?, ?)');

stmt.run('private_key_value', 'address_value', 'decimalNumber_value', 1, function(err) {
  if (err) {
    console.error('Error inserting data:', err.message);
  } else {
    console.log(`A row has been inserted with rowid ${this.lastID}`);
  }
});

stmt.finalize();

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!