Here's an outline for building a project using Laravel as the backend and React as the frontend, with the requested pages: a login page, a register user page, and a dashboard page.
Project Setup
Backend: Laravel
-
Install Laravel
composer create-project --prefer-dist laravel/laravel backend
-
Set Up Database
- Configure
.env
file with your database credentials. - Run migrations:
php artisan migrate
- Configure
-
Install Laravel Breeze (API) Laravel Breeze provides authentication scaffolding.
composer require laravel/breeze --dev php artisan breeze:install api php artisan migrate
-
Set Up API Routes Modify
routes/api.php
for login, registration, and dashboard:use App\Http\Controllers\AuthController; Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->get('/dashboard', [AuthController::class, 'dashboard']);
-
Create AuthController
php artisan make:controller AuthController
In
AuthController.php
:namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class AuthController extends Controller { public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); return response()->json(['message' => 'User registered successfully'], 201); } public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); if (!Auth::attempt($request->only('email', 'password'))) { return response()->json(['message' => 'Invalid credentials'], 401); } $token = $request->user()->createToken('auth_token')->plainTextToken; return response()->json(['access_token' => $token, 'token_type' => 'Bearer']); } public function dashboard(Request $request) { return response()->json(['message' => 'Welcome to the dashboard']); } }
Frontend: React
-
Create React App
npx create-react-app frontend cd frontend
-
Install Axios for API Requests
npm install axios
-
Set Up Routes Install React Router:
npm install react-router-dom
Create
src/routes.js
:import React from 'react'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import Login from './pages/Login'; import Register from './pages/Register'; import Dashboard from './pages/Dashboard'; const AppRoutes = () => ( <Router> <Routes> <Route path="/" element={<Login />} /> <Route path="/register" element={<Register />} /> <Route path="/dashboard" element={<Dashboard />} /> </Routes> </Router> ); export default AppRoutes;
-
Login Page Create
src/pages/Login.jsx
:import React, { useState } from 'react'; import axios from 'axios'; const Login = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleLogin = async (e) => { e.preventDefault(); try { const response = await axios.post('http://localhost:8000/api/login', { email, password }); localStorage.setItem('token', response.data.access_token); window.location.href = '/dashboard'; } catch (error) { alert('Login failed'); } }; return ( <form onSubmit={handleLogin}> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit">Login</button> </form> ); }; export default Login;
-
Register Page Create
src/pages/Register.jsx
:import React, { useState } from 'react'; import axios from 'axios'; const Register = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleRegister = async (e) => { e.preventDefault(); try { await axios.post('http://localhost:8000/api/register', { name, email, password }); alert('Registration successful'); window.location.href = '/'; } catch (error) { alert('Registration failed'); } }; return ( <form onSubmit={handleRegister}> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit">Register</button> </form> ); }; export default Register;
-
Dashboard Page Create
src/pages/Dashboard.jsx
:import React, { useEffect, useState } from 'react'; import axios from 'axios'; const Dashboard = () => { const [message, setMessage] = useState(''); useEffect(() => { const fetchDashboard = async () => { try { const token = localStorage.getItem('token'); const response = await axios.get('http://localhost:8000/api/dashboard', { headers: { Authorization: `Bearer ${token}` }, }); setMessage(response.data.message); } catch (error) { alert('Failed to load dashboard'); window.location.href = '/'; } }; fetchDashboard(); }, []); return <h1>{message}</h1>; }; export default Dashboard;
-
Integrate Routes Update
src/index.js
:import React from 'react'; import ReactDOM from 'react-dom'; import AppRoutes from './routes'; ReactDOM.render(<AppRoutes />, document.getElementById('root'));
Run the Application
-
Start Laravel server:
php artisan serve
-
Start React development server:
npm start
Now, you have a functional Laravel-React project with a login page, register page, and dashboard!
No comments:
Post a Comment