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

Nothing beats learning by doing. Here’s a brief outline of a project that integrates several of the trends and tools mentioned above:

  • 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.

Feb 11, 2025
Read More
Tutorial
python

Build a Facial Recognition Attendance System

Store the attendance data in an SQLite database for record-keeping.

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!")

Dec 10, 2024
Read More
Article

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

With Flowbite installed and configured, you can now incorporate its components into your HTML files. Flowbite offers a variety of components such as buttons, modals, navbars, and more.

Inside the src directory, create an index.html file:

Oct 24, 2024
Read More
Tutorial

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

Open your terminal or command prompt and create a new directory for your project:

   mkdir sqlite3-tutorial
   cd sqlite3-tutorial

Oct 24, 2024
Read More
Tutorial

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

  • Decentralized Applications (dApps): If you’re building an application that needs to interact with Ethereum in real-time, such as sending transactions or calling smart contract functions.
  • Wallets: If you are developing a wallet application that needs to sign and broadcast transactions.
  • Smart Contract Deployment: Use Infura to deploy or interact with smart contracts on the Ethereum blockchain.
  • Rate Limits: Etherscan’s free tier limits the number of API requests per second (usually around 5 per second). This is fine for querying data but can be limiting for large-scale applications that need to process a lot of data quickly.
  • Pricing: Etherscan offers paid tiers that increase the API request limits.

Oct 24, 2024
Read More
Tutorial
php

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

  • إضافة الأدوار والصلاحيات (Roles and Permissions)
  • حماية النقاط النهائية باستخدام مختلف أساليب التوثيق
  • إدارة تجديد رموز الوصول (refresh tokens)

إذا كنت ترغب في التوسع، يمكنك كتابة دروس إضافية حول كيفية تحسين هذه الواجهة، مثل تحسين إدارة المستخدمين والأدوار، أو كيفية إنشاء نظام إشعارات متكامل.

Sep 27, 2024
Read More
Cheatsheet
javascript css +1

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

{
  "manifest_version": 3,
  "name": "My Chrome Extension",
  "version": "1.0",
  "description": "A simple Chrome extension example.",
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "permissions": [
    "activeTab"
  ]
}
  • manifest_version: Specifies the version of the manifest file format. Version 3 is the latest and recommended version.
  • name: The name of your extension as it will appear in the Chrome Web Store and in the extension list.
  • version: The version of your extension, which must be updated with each new release.
  • description: A short description of what your extension does.
  • action: Defines the behavior of your extension's toolbar button, including the popup that will be displayed when clicked.
  • permissions: Specifies the permissions your extension needs to function. Here, activeTab allows the extension to interact with the current tab.

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

In this example, the square of the number is only recalculated when number changes, avoiding unnecessary computations.

useCallback is used to memoize functions so that they are not re-created on every render unless one of the dependencies changes. This is particularly useful when passing callbacks to child components that rely on referential equality to avoid unnecessary renders.

Aug 20, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

This command compiles and minifies your assets, outputting them to the specified directory (e.g., public/build or public/assets).

In production, the @vite directive in your Blade templates will automatically point to the compiled and versioned assets, ensuring that your application loads quickly and efficiently.

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

   npm run preview
   yarn preview

Aug 14, 2024
Read More
Tutorial
python

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

This function retrieves and prints all open positions for the BTC/USD trading pair.

This advanced Pybit tutorial covered several essential features for sophisticated trading strategies, including managing leverage, setting stop-loss orders, handling webhooks, closing orders, retrieving account balances, and fetching open positions. With these tools, you can create more resilient and automated trading systems on Bybit.

Aug 14, 2024
Read More
Tutorial
python

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

Store your API key and secret as environment variables for security:

   export BYBIT_API_KEY='your_api_key'
   export BYBIT_API_SECRET='your_api_secret'

Aug 14, 2024
Read More
Tutorial
go

Building a RESTful API with Go and Gorilla Mux

Add the deleteBook function to main.go:

func deleteBook(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	params := mux.Vars(r)
	for index, item := range books {
		if item.ID == params["id"] {
			books = append(books[:index], books[index+1:]...)
			break
		}
	}
	json.NewEncoder(w).Encode(books)
}

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

     mutation {
       addBook(title: "1984", author: "George Orwell") {
         title
         author
       }
     }
  • Flexible Queries: Allows clients to request only the data they need, reducing over-fetching.
  • Strongly Typed: Ensures data consistency and helps with error handling.
  • Single Endpoint: All data operations occur through a single endpoint, simplifying network requests.

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

No preview available for this content.

Aug 12, 2024
Read More
Tutorial
css

Building Responsive Web Designs with Tailwind CSS

   <!DOCTYPE html>
   <html lang="en">
   <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link href="output.css" rel="stylesheet">
     <title>Responsive Layout with Tailwind CSS</title>
   </head>
   <body>
     <div class="container mx-auto p-4">
       <header class="flex justify-between items-center py-4">
         <h1 class="text-3xl font-bold">My Website</h1>
         <nav>
           <ul class="flex space-x-4">
             <li><a href="#" class="text-blue-500 hover:underline">Home</a></li>
             <li><a href="#" class="text-blue-500 hover:underline">About</a></li>
             <li><a href="#" class="text-blue-500 hover:underline">Contact</a></li>
           </ul>
         </nav>
       </header>
       <main class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-6">
         <div class="bg-white p-4 shadow-md rounded">
           <h2 class="text-xl font-semibold mb-2">Card 1</h2>
           <p class="text-gray-700">This is a responsive card layout using Tailwind CSS.</p>
         </div>
         <div class="bg-white p-4 shadow-md rounded">
           <h2 class="text-xl font-semibold mb-2">Card 2</h2>
           <p class="text-gray-700">Resize the window to see the layout adjust.</p>
         </div>
         <div class="bg-white p-4 shadow-md rounded">
           <h2 class="text-xl font-semibold mb-2">Card 3</h2>
           <p class="text-gray-700">Tailwind CSS makes responsive design easy.</p>
         </div>
       </main>
     </div>
   </body>
   </html>
  • Header: The header uses Flexbox to align items horizontally and space them evenly.
  • Navigation: The navigation links are styled with Tailwind's color and hover utilities.
  • Grid Layout: The main section uses a responsive grid layout with different column numbers based on screen size breakpoints.

Aug 05, 2024
Read More
Tutorial
javascript

Building a Modern Web Application with React and Redux

   npx create-react-app my-react-app

This command will create a new directory called my-react-app with all the necessary files and dependencies.

Aug 05, 2024
Read More
Tutorial
python

Creating a Simple REST API with Flask

  • Get all items:
  curl http://127.0.0.1:5000/api/items

Aug 03, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!