How to Build a Dashboard with React and Laravel

We earn commissions when you shop through the links below.

If you’ve ever wondered how to build a dashboard with React and Laravel, you’re in good company. This stack is one of the most productive combinations in full-stack development — Laravel handles the API layer with elegance, and React gives you the component model you need to build interactive UIs. In this guide, I’ll walk you through a practical, production-ready approach from setting up the API to rendering live charts on the frontend.

Why React + Laravel?

Laravel’s expressive routing, Eloquent ORM, and built-in API resource classes make it trivial to expose clean JSON endpoints. React’s ecosystem — with libraries like Recharts, React Query, and Axios — handles data fetching and visualization with minimal boilerplate. Together, they let you move fast without sacrificing structure.

If you want to accelerate development significantly, I recommend using Cursor as your AI-powered IDE. It understands both PHP and JavaScript deeply and can generate boilerplate, suggest refactors, and autocomplete complex logic across both sides of the stack simultaneously.

Project Architecture Overview

We’ll build a simple analytics dashboard with the following structure:

  • Laravel backend: REST API with authentication via Laravel Sanctum
  • React frontend: Vite-powered SPA with Axios, React Query, and Recharts
  • Data: A metrics endpoint returning time-series data for charts

You can host both under one domain (Laravel serves the React build) or deploy them separately. I’ll cover the decoupled approach since it’s more flexible.

Step 1: Set Up the Laravel API

Start with a fresh Laravel project and install Sanctum for SPA authentication:

composer create-project laravel/laravel dashboard-api
cd dashboard-api
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Configure your cors.php to allow requests from your React dev server:

// config/cors.php
'allowed_origins' => ['http://localhost:5173'],
'supports_credentials' => true,

Now create a metrics controller that returns time-series data:

// app/Http/Controllers/Api/MetricsController.php
map(function ($daysAgo) {
            return [
                'date' => Carbon::now()->subDays(29 - $daysAgo)->format('M d'),
                'revenue' => rand(1200, 8000),
                'users' => rand(80, 500),
            ];
        });

        return response()->json($data);
    }
}

Register the route inside routes/api.php:

use App\Http\Controllers\Api\MetricsController;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/metrics/revenue', [MetricsController::class, 'revenue']);
});

Step 2: Bootstrap the React Frontend

Create a new Vite React project and install dependencies:

npm create vite@latest dashboard-ui -- --template react
cd dashboard-ui
npm install axios @tanstack/react-query recharts react-router-dom

Set up an Axios instance with credentials support:

// src/lib/axios.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8000/api',
  withCredentials: true,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
});

export default api;

Step 3: Fetching Data with React Query

Wrap your app with QueryClientProvider in main.jsx, then create a custom hook for your metrics:

// src/hooks/useRevenue.js
import { useQuery } from '@tanstack/react-query';
import api from '../lib/axios';

export function useRevenue() {
  return useQuery({
    queryKey: ['metrics', 'revenue'],
    queryFn: async () => {
      const { data } = await api.get('/metrics/revenue');
      return data;
    },
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
}

React Query handles caching, background refetching, and loading states out of the box. This is exactly the kind of pattern that makes knowing how to build a dashboard with React and Laravel so powerful — you get predictable data flow on both sides.

Step 4: Building the Dashboard Layout

Create a simple dashboard page with stat cards and a chart:

// src/pages/Dashboard.jsx
import { useRevenue } from '../hooks/useRevenue';
import {
  AreaChart, Area, XAxis, YAxis,
  CartesianGrid, Tooltip, ResponsiveContainer
} from 'recharts';

export default function Dashboard() {
  const { data, isLoading, isError } = useRevenue();

  if (isLoading) return 

Loading metrics...

; if (isError) return

Failed to load data.

; const totalRevenue = data.reduce((sum, d) => sum + d.revenue, 0); const totalUsers = data.reduce((sum, d) => sum + d.users, 0); return (

Analytics Dashboard

Total Revenue (30d)

${totalRevenue.toLocaleString()}

Total Users (30d)

{totalUsers.toLocaleString()}

Revenue Over Time

); }

Step 5: Authentication Flow

Sanctum uses cookie-based authentication for SPAs. Before making authenticated requests, hit the CSRF endpoint:

// src/lib/auth.js
import api from './axios';

export async function login(email, password) {
  // Get CSRF cookie first
  await axios.get('http://localhost:8000/sanctum/csrf-cookie', {
    withCredentials: true,
  });

  return api.post('/login', { email, password });
}

export async function logout() {
  return api.post('/logout');
}

Create corresponding login/logout routes in your Laravel API using the built-in auth controllers or a simple custom one that calls Auth::attempt().

Step 6: Deploying the Stack

For deployment, I lean toward Railway for this kind of full-stack setup. You can deploy your Laravel API and a static frontend host from the same dashboard, configure environment variables, and get a PostgreSQL database provisioned in minutes. It removes a lot of the DevOps friction that slows down dashboard projects.

When deploying Laravel, make sure to set:

APP_ENV=production
APP_KEY=base64:...
SANCTUM_STATEFUL_DOMAINS=yourdomain.com
SESSION_DOMAIN=.yourdomain.com

Build your React app with npm run build and either serve it from Laravel’s public directory or deploy it to a static hosting service and point it at your API domain.

Tips for Production Dashboards

  • Use Laravel API Resources to shape your JSON output and avoid exposing raw database columns
  • Add caching to expensive metric queries with Cache::remember() — dashboards often fetch the same data across many users
  • Implement role-based access using Laravel Gates or Policies so different users see different metrics
  • Paginate large datasets and use query parameters to filter by date range rather than returning all records
  • Debounce filter inputs on the React side to avoid hammering the API on every keystroke

Going Deeper

If you want a more structured learning path covering both Laravel and React in depth, Udemy has several well-rated courses that cover full-stack SPA development with this exact combination. Worth it if you prefer video walkthroughs alongside a project like this.

Wrapping Up

Understanding how to build a dashboard with React and Laravel comes down to three things: a clean API contract, smart data fetching on the frontend, and a component structure that keeps your charts and stat cards reusable. The pattern I’ve outlined here scales well — I’ve used variations of it in production SaaS apps handling hundreds of thousands of rows of time-series data.

Start with the basic metrics endpoint, get the chart rendering, then layer in authentication and role-based data filtering. Once that foundation is solid, you can extend it with WebSocket-powered live updates, export-to-CSV features, or multi-tenant data scoping — all without rearchitecting anything fundamental.