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

import os
import face_recognition
import cv2
import pickle

# Path to dataset
DATASET_PATH = "dataset"
ENCODINGS_FILE = "encodings.pickle"

def encode_faces():
    known_encodings = []
    known_names = []

    # Iterate through each person's folder
    for person in os.listdir(DATASET_PATH):
        person_path = os.path.join(DATASET_PATH, person)
        if not os.path.isdir(person_path):
            continue

        # Process each image
        for img_file in os.listdir(person_path):
            img_path = os.path.join(person_path, img_file)
            image = face_recognition.load_image_file(img_path)
            face_encodings = face_recognition.face_encodings(image)

            if face_encodings:
                known_encodings.append(face_encodings[0])
                known_names.append(person)

    # Save encodings to a file
    with open(ENCODINGS_FILE, "wb") as f:
        pickle.dump({"encodings": known_encodings, "names": known_names}, f)

    print("Encodings saved!")

encode_faces()

Use the saved encodings to identify individuals in real-time.

Dec 10, 2024
Read More
Article

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

Explore Flowbite's documentation to discover a wide range of components and utilities. Customize components to fit your project's design requirements, leveraging Tailwind CSS's utility classes for flexibility.

Integrating Flowbite with Tailwind CSS significantly accelerates your UI development process by providing ready-to-use, customizable components that adhere to modern design principles. By following this tutorial, you've successfully:

Oct 24, 2024
Read More
Tutorial

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

Add the following code at the end of your app.js file, outside the db.serialize() block:

// Close the database connection
db.close((err) => {
  if (err) {
    console.error('Error closing the database connection:', err.message);
  } else {
    console.log('Database connection closed.');
  }
});

Oct 24, 2024
Read More
Tutorial

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

In this tutorial, we will compare Etherscan and Infura, two popular services for interacting with the Ethereum blockchain. Both provide APIs, but they serve different purposes and are suited for different types of applications. By understanding the strengths of each, you can choose the right one based on your specific use case, whether it involves querying blockchain data or interacting with the Ethereum network in real-time.

  • Basic understanding of Ethereum and blockchain concepts.
  • Familiarity with APIs and programming in Node.js or any other language.

Oct 24, 2024
Read More
Tutorial
php

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

composer create-project --prefer-dist laravel/laravel laravel-passport-api

ثم توجه إلى مجلد المشروع:

Sep 27, 2024
Read More
Cheatsheet
javascript css +1

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

  • chrome.tabs.query: This API retrieves the active tab in the current window.
  • chrome.scripting.executeScript: Executes a script in the context of the active tab. In this case, it changes the background color of the webpage.

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:

Aug 20, 2024
Read More
Cheatsheet
mysql

MySQL Cheatsheet: Comprehensive Guide with Examples

No preview available for this content.

Aug 20, 2024
Read More
Cheatsheet
javascript

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

import React from 'react';

function ItemList({ items }) {
  return (
    <>
      {items.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </>
  );
}

For very large lists, consider using windowing libraries like react-window to only render a subset of the list items that are currently visible.

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

If you selected React during the setup, your project is already configured with React. You can start building React components directly.

Here's a simple example of a React component:

Aug 14, 2024
Read More
Tutorial
python

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

In leveraged trading, managing your leverage is crucial for controlling risk and maximizing potential gains. Pybit allows you to adjust leverage on specific trading pairs.

The following function sets the leverage for a specific trading pair:

Aug 14, 2024
Read More
Tutorial
python

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

In the rapidly evolving world of cryptocurrency trading, accessing and interacting with exchange APIs is essential for automated trading and data analysis. Pybit is a Python wrapper for the Bybit API, making it easier to access and interact with Bybit's functionalities using Python. In this tutorial, we'll walk you through the basics of setting up Pybit, fetching market data, and executing trades.

  • Basic knowledge of Python.
  • A Bybit account.
  • Installed Python packages: pybit, requests.

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

   curl -X DELETE http://localhost:8000/books/b1

In this tutorial, we built a simple RESTful API using Go and Gorilla Mux. We covered:

Aug 12, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

  • Fetch Books
  query {
    books {
      title
      author
    }
  }

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

  • Add a Book
     mutation {
       addBook(title: "1984", author: "George Orwell") {
         title
         author
       }
     }

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

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

import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path

function UserList() {
    const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;

Aug 12, 2024
Read More
Tutorial
css

Building Responsive Web Designs with Tailwind CSS

You've successfully set up Tailwind CSS and built a responsive web layout. Tailwind's utility-first approach provides a flexible and efficient way to create modern web designs without writing custom CSS.

  • Explore Tailwind CSS's components and utilities to enhance your designs.
  • Learn about Tailwind's JIT (Just-in-Time) mode for faster build times and smaller file sizes.
  • Experiment with Tailwind CSS plugins for additional functionality.

Aug 05, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

This code sets up a simple Redux store with an initial state containing a count property and a reducer function to handle INCREMENT and DECREMENT actions.

In the src/index.js file, wrap your <App /> component with the <Provider> component from react-redux, passing it the store as a prop.

Aug 05, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

Visit http://127.0.0.1:5000/ in your browser to see the welcome message.

from flask import Flask, jsonify

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

if __name__ == '__main__':
    app.run(debug=True)

Aug 03, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!