Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to implement react js with laravel backend

Implement react js below laravel 8
Implement react js above laravel 8
How to post data in laravel using react js

Implement react js below laravel 8

Install Node.js and NPM
Ensure that Node.js and npm are installed on your system. You can download them from Node.js official site.

Check versions:

node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

Install React in Laravel
Install the necessary dependencies to use React in your Laravel application:

composer require laravel/ui
php artisan ui react
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Create a React Component
Create a React component for the booking page.

Navigate to resources/js/components/ and create a new file, e.g., BookingComponent.jsx:

import React, { useState, useEffect } from "react";

const BookingComponent = ({ vehicleId, shopId, shopName }) => {
  const [vehicle, setVehicle] = useState({});
  const [bookings, setBookings] = useState([]);
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [pricePerDay, setPricePerDay] = useState(0);
  const [totalPrice, setTotalPrice] = useState(0);

  useEffect(() => {
    fetchVehicleDetails(vehicleId);
    fetchBookings(vehicleId);
  }, [vehicleId]);

  const fetchVehicleDetails = async (id) => {
    try {
      const response = await fetch(`/api/vehicle/${id}`);
      const data = await response.json();
      setVehicle(data);
      setPricePerDay(data.price);
    } catch (error) {
      console.error("Error fetching vehicle details:", error);
    }
  };

  const fetchBookings = async (id) => {
    try {
      const response = await fetch(`/api/getbookings/${id}`);
      const data = await response.json();
      setBookings(data);
    } catch (error) {
      console.error("Error fetching bookings:", error);
    }
  };

  const handleDateChange = (e, type) => {
    const value = e.target.value;
    if (type === "start") setStartDate(value);
    if (type === "end") setEndDate(value);
    validateDateRange(value, type);
    calculateTotalPrice();
  };

  const validateDateRange = (value, type) => {
    for (let booking of bookings) {
      const conflict =
        (type === "start" && value >= booking.start_date && value <= booking.end_date) ||
        (type === "end" && value >= booking.start_date && value <= booking.end_date);
      if (conflict) {
        alert(
          `The selected date range overlaps with an existing booking.\nConflicting Booking:\nStart Date: ${booking.start_date}\nEnd Date: ${booking.end_date}`
        );
        if (type === "start") setStartDate("");
        if (type === "end") setEndDate("");
        return;
      }
    }
  };

  const calculateTotalPrice = () => {
    if (startDate && endDate) {
      const start = new Date(startDate);
      const end = new Date(endDate);
      const days = Math.ceil((end - start) / (1000 * 3600 * 24));
      setTotalPrice(days * pricePerDay);
    }
  };

  return (
    <div>
      <h2>Booking Details</h2>
      <form action="/api/confirmbooking" method="POST">
        <input type="hidden" name="vechicle_id" value={vehicle.id} />
        <input type="hidden" name="shop_id" value={shopId} />
        <input type="hidden" name="price" value={pricePerDay} />
        <div>
          <label>Start Date:</label>
          <input
            type="date"
            name="start_date"
            value={startDate}
            onChange={(e) => handleDateChange(e, "start")}
            min={new Date().toISOString().split("T")[0]}
          />
        </div>
        <div>
          <label>End Date:</label>
          <input
            type="date"
            name="end_date"
            value={endDate}
            onChange={(e) => handleDateChange(e, "end")}
            min={startDate}
          />
        </div>
        <div>
          <label>Price Per Day:</label>
          <input type="number" value={pricePerDay} readOnly />
        </div>
        <div>
          <label>Total Price:</label>
          <input type="number" name="total_price" value={totalPrice} readOnly />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default BookingComponent;
Enter fullscreen mode Exit fullscreen mode
  1. Call React Component in Blade File Update your booking.blade.php file to render the React component:
@extends('layouts.rentcar')

@section('content')
<div id="booking-root"></div>
<script src="{{ mix('js/app.js') }}"></script>
<script>
    ReactDOM.render(
        React.createElement(BookingComponent, {
            vehicleId: "{{ $vehicle->id }}",
            shopId: "{{ $shopid }}",
            shopName: "{{ $Shopname }}"
        }),
        document.getElementById("booking-root")
    );
</script>
@endsection
Enter fullscreen mode Exit fullscreen mode
  1. Add API Routes in Laravel Add the necessary API routes for fetching vehicle details and bookings.

In routes/api.php:

use App\Http\Controllers\VehicleController;

Route::get('/vehicle/{id}', [VehicleController::class, 'show']);
Route::get('/getbookings/{id}', [VehicleController::class, 'getBookings']);
Enter fullscreen mode Exit fullscreen mode
  1. Create API Controller Create a controller to handle API requests:
php artisan make:controller VehicleController
Enter fullscreen mode Exit fullscreen mode

Update VehicleController.php:

namespace App\Http\Controllers;

use App\Models\AddVechicles;
use App\Models\Booking;
use Illuminate\Http\Request;

class VehicleController extends Controller
{
    public function show($id)
    {
        $vehicle = AddVechicles::find($id);
        return response()->json($vehicle);
    }

    public function getBookings($id)
    {
        $bookings = Booking::where('vechicle_id', $id)->get(['start_date', 'end_date']);
        return response()->json($bookings);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Compile Assets Compile the React component:
npm run dev
Enter fullscreen mode Exit fullscreen mode

Image description

What is mix('js/app.js')?
mix() is a Laravel helper function.
It generates the correct path to your compiled assets using Laravel Mix, ensuring cache-busting by appending a unique version hash to the file name (e.g., app.js?id=123456).
app.js is typically the entry point for your JavaScript or React application, which Laravel Mix compiles.

Implement react js above laravel 8

Install Node.js and NPM
Ensure that Node.js and npm are installed on your system. You can download them from Node.js official site.

Check versions:

node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

Install React in Laravel
Install the necessary dependencies to use React in your Laravel application:

composer require laravel/ui
php artisan ui react
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

===================or===========================

npm install react react-dom --legacy-peer-deps
Enter fullscreen mode Exit fullscreen mode
npm install @vitejs/plugin-react --save-dev
Enter fullscreen mode Exit fullscreen mode

Image description

Changes/Steps to Enable React

  1. Verify Vite Configuration Your vite.config.js file already includes the necessary React and Laravel plugins. It looks good. Here's the correct setup for reference:

for production

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

export default defineConfig({
    plugins: [
        laravel({
            input: [

                'resources/js/app.jsx',
            ],
            refresh: true,
        }),
        react(),
    ],
    base: process.env.APP_URL || '/', // Ensure correct base path
});
Enter fullscreen mode Exit fullscreen mode

For Local

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

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss', // If using SCSS
                'resources/js/app.jsx',   // React entry point
            ],
            refresh: true, // Enables hot-reloading
        }),
        react(), // Enables React support
    ],
});
Enter fullscreen mode Exit fullscreen mode

Image description

Folder Structure

Image description

Blade Template Example

<tbody id="react-booking-table" data-bookings="{{ json_encode($data) }}"></tbody>
@vite('resources/js/app.jsx')
Enter fullscreen mode Exit fullscreen mode
<div class="userdashboard">
        <div class="container-fluid">
            <div class="dashboard-container">
                <div class="tab-contents">
                    <!-- <div class="tabpane"> -->
                    <div class="contentd" id="order-history">
                        <h3 class="centered-heading">Booking History</h3>
                      @include('vender/layouts/bookings_navbar')
                        <div class="ordercontainer">
                        <table id="example" class="display">
    <thead>
        <tr>
            <th>ID</th>
            <th>Pickup And destination</th>
            <th>Vehicle Type</th>
            <th>Brand</th>
            <th>Model</th>
            <th>Price</th>
            <th>Start_date</th>
            <th>End_date</th>
            <th>Number</th>
            <th>Email</th>
            <th>Status</th>
        </tr>
    </thead>
    <!-- <tbody id="react-booking-table" data-bookings="{{ json_encode($data, JSON_PRETTY_PRINT) }}"></tbody> -->
    <tbody id="react-booking-table" data-bookings="{{ json_encode($data) }}"></tbody>
    <!-- <tbody id="react-booking-table" data-bookings='[{"id":1,"destination":"City A","vechicle_type":"Car","brand":"Toyota","model":"Camry","price":100,"start_date":"2025-01-01","end_date":"2025-01-05","number":"1234567890","email":"example@test.com","status":0}]'></tbody> -->
</table>
                        </div>
                    </div>
                    <!-- </div> -->
                </div>
            </div>
        </div>
    </div>


    <div class="modal" id="editModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <form id="contact" action="{{ route('change_status') }}" method="POST">
            @csrf
            <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                <div class="modal-header">
                    <h5 class="modal-title">Edit Status</h5>
                </div>
                <input type="hidden" id="postIdInput" name="id">
                <select id="editStatusInput" class="form-control" name="status">
                    <!-- Options will be dynamically generated -->
                </select>
                <button type="submit" class="btn-primary" id="saveEdit">Save Changes</button>
            </div>
        </form>
    </div>
</div> 
        </main>
        <!-- MAIN -->
    </section>
    <!-- CONTENT -->
    @vite('resources/js/app.jsx') 
Enter fullscreen mode Exit fullscreen mode

React (app.jsx) Example

import React from 'react';
import ReactDOM from 'react-dom';
import BookingRow from './components/BookingRow';

const bookingData = JSON.parse(document.getElementById('react-booking-table').dataset.bookings);

ReactDOM.render(
    <>
        {bookingData.map((booking, index) => (
            <BookingRow
                key={index}
                id={index + 1}
                destination={booking.destination}
                vehicleType={booking.vechicle_type}
                brand={booking.brand}
                model={booking.model}
                price={booking.price}
                startDate={booking.start_date}
                endDate={booking.end_date}
                number={booking.number}
                email={booking.email}
                status={booking.status}
            />
        ))}
    </>,
    document.getElementById('react-booking-table')
);
Enter fullscreen mode Exit fullscreen mode

Verify Component Rendering
In resources/js/components/BookingRow.jsx, ensure props are correctly passed and rendered.

Example BookingRow.jsx:

import React from 'react';

const BookingRow = ({ id, destination, vehicleType, brand, model, price, startDate, endDate, number, email, status }) => {
    return (
        <tr>
            <td>{id}</td>
            <td>{destination}</td>
            <td>{vehicleType}</td>
            <td>{brand}</td>
            <td>{model}</td>
            <td>{price}</td>
            <td>{startDate}</td>
            <td>{endDate}</td>
            <td>{number}</td>
            <td>{email}</td>
            <td>
                {status == '0' && <button className="edit-status button button-waiting" data-id={id} data-status="0">Waiting</button>}
                {status == '1' && <button className="edit-status btn-success" data-id={id} data-status="1">Confirm</button>}
                {status == '2' && <button className="edit-status btn-primary" data-id={id} data-status="2">Complete</button>}
            </td>
        </tr>
    );
};

export default BookingRow;
Enter fullscreen mode Exit fullscreen mode

For any change in jsx to see changes are effective are not run these commands

nvm install 22
npm run dev
npm run build
===========for permiision=========
chown -R daemon:daemon .
Enter fullscreen mode Exit fullscreen mode

output

Image description

Image description

if vite.config.js not exist in production then run it

npm install @vitejs/plugin-react --save-dev
Enter fullscreen mode Exit fullscreen mode
npm install redux react-redux
Enter fullscreen mode Exit fullscreen mode
012  npm install @vitejs/plugin-react --save-dev
 2013  node -v
 2014  nvm install 22
 2015  npm install @vitejs/plugin-react --save-dev
 2016  npm run dev
 2017  npm install react react-dom
 2018  npm install @vitejs/plugin-react
 2019  npm install @vitejs/plugin-react --save-dev
 2020  npm run dev
 2021  ./pull.js
 2022  npm run build
 2023  npm run dev
 2024  npm run build
 2025  ./pull.sh
 2026  git stash save
 2027  ./pull.sh
 2028  npm install sass@latest
 2029  npm install bootstrap@latest
 2030  npm run dev
 2031  nvm install 22 // install node js version node-v 22
 2032  npm run dev
 2033  npm install @vitejs/plugin-react --save-dev
 2034  npm run dev
 2035  npm install @vitejs/plugin-react --save-dev
 2036  npm run dev
 2037  npm install react react-dom
 2038  npm install @vitejs/plugin-react
Enter fullscreen mode Exit fullscreen mode

How to post data in laravel using react js

must add

 <meta name="csrf-token" content="{{ csrf_token() }}">
Enter fullscreen mode Exit fullscreen mode
 <meta name="csrf-token" content="{{ csrf_token() }}">
<div class="userdashboard">
        <div class="container-fluid">
            <div class="dashboard-container">
                <div class="tab-contents">
                    <!-- <div class="tabpane"> -->
                    <div class="contentd" id="order-history">
                        <h3 class="centered-heading">Booking History</h3>
                      @include('vender/layouts/bookings_navbar')
                        <div class="ordercontainer">
                        <table id="example" class="display">
    <thead>
        <tr>
            <th>ID</th>
            <th>Pickup And destination</th>
            <th>Vehicle Type</th>
            <th>Brand</th>
            <th>Model</th>
            <th>Price</th>
            <th>Start_date</th>
            <th>End_date</th>
            <th>Number</th>
            <th>Email</th>
            <th>Status</th>
        </tr>
    </thead>
    <!-- <tbody id="react-booking-table" data-bookings="{{ json_encode($data, JSON_PRETTY_PRINT) }}"></tbody> -->
    <tbody id="react-booking-table" data-bookings="{{ json_encode($data) }}"></tbody>
    <!-- <tbody id="react-booking-table" data-bookings='[{"id":1,"destination":"City A","vechicle_type":"Car","brand":"Toyota","model":"Camry","price":100,"start_date":"2025-01-01","end_date":"2025-01-05","number":"1234567890","email":"example@test.com","status":0}]'></tbody> -->
</table>
                        </div>
                    </div>
                    <!-- </div> -->
                </div>
            </div>
        </div>
    </div>



        </main>
        <!-- MAIN -->
    </section>
    <!-- CONTENT -->
    @vite('resources/js/app.jsx') 
Enter fullscreen mode Exit fullscreen mode
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        laravel({
            input: [

                'resources/js/app.jsx',
            ],
            refresh: true,
        }),
        react(),
    ],
    base: process.env.APP_URL || '/', // Ensure correct base path
});
Enter fullscreen mode Exit fullscreen mode
import React from 'react';
import ReactDOM from 'react-dom/client'; // Correct import for React 18+

import BookingRow from './components/BookingRow';

const bookingData = JSON.parse(document.getElementById('react-booking-table').dataset.bookings);

const rootElement = document.getElementById('react-booking-table');
const root = ReactDOM.createRoot(rootElement);

root.render(
    <>
        {bookingData.map((booking, index) => (
            <BookingRow
                key={index}
                id={index + 1}
                destination={booking.destination}
                vehicleType={booking.vechicle_type}
                brand={booking.brand}
                model={booking.model}
                price={booking.price}
                startDate={booking.start_date}
                endDate={booking.end_date}
                number={booking.number}
                email={booking.email}
                status={booking.status}
            />
        ))}
    </>
);

Enter fullscreen mode Exit fullscreen mode
  const handleSaveChanges = async () => {
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        try {
            const response = await axios.post('/partner/change_status', 
                {
                    id,                // Booking ID
                    status: currentStatus, // New Status
                },
                {
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                }
            );

            console.log('Response:', response.data);
            if (response.data.success) {
                alert('Status updated successfully');
                handleCloseModal();
            } else {
                alert('Failed to update status');
            }
        } catch (error) {
            console.error('Error updating status:', error);
            alert('An error occurred while updating status');
        }
    };
Enter fullscreen mode Exit fullscreen mode

Top comments (0)