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.

Continue Reading

Discover more amazing content handpicked just for you

Article

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

Understanding these trends not only helps you stay relevant but also opens doors to innovative project ideas and streamlined workflows.

Jamstack (JavaScript, APIs, and Markup) is redefining the way we build websites. By decoupling the frontend from the backend, developers can create faster, more secure, and scalable applications. Key benefits include:

Feb 11, 2025
Read More
Tutorial
python

Build a Facial Recognition Attendance System

In this tutorial, we’ll create a facial recognition-based attendance system using Python. This project combines computer vision, machine learning, and database management to automate attendance tracking for workplaces, schools, or events. By the end, you’ll have a working application that can detect faces, recognize individuals, and log their attendance into a database.

Traditional attendance systems like manual sign-ins or RFID cards are time-consuming and prone to errors. Facial recognition offers a fast, contactless, and reliable solution.

Dec 10, 2024
Read More
Article

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

Generate tailwind.config.js and postcss.config.js files by running:

   npx tailwindcss init -p

Oct 24, 2024
Read More
Tutorial

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

The sqlite3 package is a Node.js library that provides a straightforward API to interact with SQLite databases. It allows you to perform SQL operations such as creating tables, inserting data, querying data, and more, all from within your Node.js applications.

Before you begin, ensure you have the following:

Oct 24, 2024
Read More
Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

In some cases, you might want to use both Etherscan and Infura. For example, you might use Etherscan to query transaction histories or token transfers, and Infura to send transactions or deploy contracts.

  • Etherscan: Use to fetch transaction history and display it in your dApp.
  • Infura: Use to allow users to send transactions or interact with smart contracts.

Oct 24, 2024
Read More
Tutorial
php

بناء API متقدم باستخدام Laravel Passport للتوثيق

افتح ملف routes/api.php وأضف المسارات الخاصة بالتسجيل وتسجيل الدخول:

use App\Http\Controllers\AuthController;

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);

// مسار للحصول على بيانات المستخدم المسجل
Route::middleware('auth:api')->get('/user', [AuthController::class, 'user']);

Sep 27, 2024
Read More
Cheatsheet
javascript css +1

Building a Chrome Extension: A Step-by-Step Tutorial

For a complete extension, you'll need to add icons that represent your extension in the Chrome toolbar. Create an images folder in your project directory and add three icons with the following dimensions:

  • icon16.png (16x16 pixels)
  • icon48.png (48x48 pixels)
  • icon128.png (128x128 pixels)

Aug 20, 2024
Read More
Cheatsheet
mysql

MySQL Cheatsheet: Comprehensive Guide with Examples

This MySQL cheatsheet provides a comprehensive overview of the most commonly used MySQL commands, complete with examples to help you quickly find the information you need. Whether you're creating and managing databases, writing queries, or handling transactions, this guide serves as a quick reference to help you work more efficiently with MySQL.

Aug 20, 2024
Read More
Cheatsheet
javascript

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;

In this example, LazyComponent is only loaded when it’s needed, and a loading message is displayed while it’s being fetched.

Aug 20, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

Navigate to your project directory:

   cd my-vite-laravel-app

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

In your JavaScript files, you can access this variable using:

   const apiUrl = import.meta.env.VITE_API_URL;

Aug 14, 2024
Read More
Tutorial
python

Advanced Pybit Tutorial: Managing Leverage, Stop-Loss Orders, Webhooks, and More

This Flask app listens for POST requests on /webhook and prints the received data. You can expand this to handle specific webhook events like order fills, price alerts, etc.

Managing open orders and closing positions is essential for effective trading. Pybit makes it straightforward to close orders.

Aug 14, 2024
Read More
Tutorial
python

A Beginner's Guide to Pybit: Interacting with the Bybit API

One of the most common uses of exchange APIs is to fetch real-time market data. Let's start by retrieving the current price of a trading pair.

Use the following code to fetch the latest price of BTC/USD:

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

Add the createBook function to main.go:

func createBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var book Book
	_ = json.NewDecoder(r.Body).Decode(&book)
	book.ID = "b" + string(len(books)+1) // Simple ID generation
	books = append(books, book)
	json.NewEncoder(w).Encode(book)
}

Aug 12, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

In this section, we will set up a simple GraphQL server using Node.js, Express, and Apollo Server. We will create an API for managing a list of books.

  • Basic knowledge of Node.js and JavaScript
  • Node.js and npm installed on your machine

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

   node index.js

Open a browser and go to http://localhost:4000/graphql. You'll see the Apollo GraphQL Playground, where you can test your queries and mutations.

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let isMounted = true; // Track if component is mounted

        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await fetch(url, options);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                if (isMounted) {
                    setData(result);
                }
            } catch (error) {
                if (isMounted) {
                    setError(error);
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false; // Cleanup to avoid setting state on unmounted component
        };
    }, [url, options]);

    return { data, loading, error };
}

export default useFetch;

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.

Aug 12, 2024
Read More
Tutorial
css

Building Responsive Web Designs with Tailwind CSS

Tailwind CSS is a utility-first CSS framework that allows developers to create responsive and modern web designs quickly. Instead of writing custom CSS, you use predefined classes directly in your HTML to style components. In this tutorial, we'll set up Tailwind CSS and build a responsive webpage using its powerful utility classes.

You should have a basic understanding of HTML and CSS. Make sure you have Node.js and npm installed on your machine, as we will use them to set up Tailwind CSS.

Aug 05, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

   import React from 'react';
   import Counter from './Counter';

   const App = () => {
     return (
       <div className="App">
         <h1>React and Redux Counter</h1>
         <Counter />
       </div>
     );
   };

   export default App;

Congratulations! You have successfully set up a React application with Redux for state management. You created a simple counter application to demonstrate the integration of Redux in a React project. From here, you can explore more advanced concepts like middleware, asynchronous actions, and integrating APIs to build more complex applications.

Aug 05, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

  • Update an existing item:
  curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item 2"}' http://127.0.0.1:5000/api/items/2

Aug 03, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!