In this article, I would like to show you how to make a simple login form in React. Login form in React with Laravel.
I will use Laravel for Rest API. Because We must need one server-side language for database transactions. I will use Material UI for Form designing. Learn more about Material UI.
React will use Axios or fetch for communicating with Laravel . Laravel uses REST API for sending and receiving request from REACT JS .


Now We start with Server Side part ( Laravel Part )
Making REST API in Laravel is very easy. First, make a Database with the named react_laravel_signup.
I am using Laravel 8 so I didn’t face CORS Error If you’re using Laravel 5 or 6 You will face CORS Errors. So Always enable CORS in Laravel.
--
-- Database: `react_laravel_signup`
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
Now First make routes for REST API so I will make two URLs for REST API. ( app/routes/api.php ) . We always use api.php to make REST API Routes.
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\AuthController;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register',[UserController::class,'register']); // Singup URL
Route::post('/reactlogin',[UserController::class,'login']); // lOGIN url
Now make a Controller named UserController . ( app/http/controllers/UserController.php )
UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Redirect,Response,File;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
function register(Request $req)
{
$name = $req->input('name');
$email = $req->input('email');
$password = Hash::make($req->input('password'));
DB::table('users')->insert([
'name' => $name,
'email' => $email ,
'password'=> $password
]);
}
function login(Request $req)
{
$email = $req->input('email');
$password = $req->input('password');
$user = DB::table('users')->where('email',$email)->first();
if(!Hash::check($password, $user->password))
{
echo "Not Matched";
}
else
{
//$user = DB::table('users')->where('email',$email)->first();
echo $user->email;
}
}
}
I didn’t use model because I used Query Builder feature of Laravel so I didn’t require Model . If you are using Laravel Eloquent then you need Model file.
React Part Starts here
First install some packages here . To Install a package write npm install axios or yarn add axios
"@material-ui/core": "^4.11.4",
"axios": "^0.21.1",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
I have made three Components in SRC Folder of React. Home.js, Login.js & Singup.js
Singup.js ( src/Singup.js))
import React from 'react'
import { Grid,Paper, Avatar, TextField, Button, Typography } from '@material-ui/core'
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import { Link, NavLink } from "react-router-dom";
import {useState} from 'react';
import axios from 'axios';
const Signup=()=>{
const paperStyle={padding :20,height:'70vh',width:280, margin:"20px auto"}
const avatarStyle={backgroundColor:'#3370bd'}
const btnstyle={margin:'8px 0'}
const[errors,setErrors] = useState('');
const [user, setUser] = useState({
name: "",
email: "",
password:""
});
const {name, email,password} = user;
const onInputChange = e => {
setUser({ ...user, [e.target.name]: e.target.value });
};
async function signup()
{
let result = await axios.post("http://localhost:8000/api/register",user);
setErrors('Registration Successful')
setUser({name:"",email:"",password:""}) // To Clear all fields
}
return(
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align='center'>
<Avatar style={avatarStyle}><LockOutlinedIcon/></Avatar>
<h2>Sign Up</h2>
<h3 style={{color:"green"}}>{errors}</h3>
</Grid>
<TextField label='Name' name="name" value={name} onChange={e => onInputChange(e)} placeholder='Enter Name' type='text' fullWidth required/>
<TextField label='Email' name="email" value={email} onChange={e => onInputChange(e)} placeholder='Enter Email' type='text' fullWidth required/>
<TextField label='Password' name="password" value={password} onChange={e => onInputChange(e)} placeholder='Enter password' type='text' fullWidth required/>
<Button type='submit' onClick={signup} color='primary' variant="contained" style={btnstyle} fullWidth>Singup</Button>
<Typography>Click Here for
<NavLink to="/">
<span style={{marginLeft:"4px"}}>Login</span>
</NavLink>
</Typography>
</Paper>
</Grid>
)
}
export default Signup
Now Make Login Page ( src/Login.js)
Login.js
import React from 'react'
import { Grid,Paper, Avatar, TextField, Button, Typography,Link as Nv } from '@material-ui/core'
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import { Link, NavLink } from "react-router-dom";
import {useState} from 'react';
import axios from 'axios';
import { useHistory, useParams } from "react-router-dom";
const Login=()=>{
const paperStyle={padding :20,height:'70vh',width:280, margin:"20px auto"}
const avatarStyle={backgroundColor:'#3370bd'}
const btnstyle={margin:'8px 0'}
const [msg,setMsg] = useState('');
const [username, setUsername] = useState("");
const [pass, setPass] = useState("");
const [user, setUser] = useState({
email: "",
password:""
});
let history = useHistory();
const {email,password} = user;
const onInputChange = e => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const signIn = () =>
{
const users = { username }; // To Store Email in Localstore and send to Home Page
if(user.email === '')
{
alert('Email Field is empty')
}
else if(user.password === '')
{
alert('Pass Field is empty')
}
axios.post("http://localhost:8000/api/reactlogin/",user)
.then(response => {
setMsg(response.data);
localStorage.setItem("users",response.data);
history.push("/Home");
});
}
return(
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align='center'>
<Avatar style={avatarStyle}><LockOutlinedIcon/></Avatar>
<h2>Sign In</h2>
<h4 style={{color:"green"}}>{msg}</h4>
</Grid>
<TextField label='Email' name="email" value={email} onChange={e => onInputChange(e)} placeholder='Enter Email' type='text' fullWidth required/>
<TextField label='Password' name="password" value={password} onChange={e => onInputChange(e)} placeholder='Enter password' type='text' fullWidth required/>
<Button type='submit' onClick={signIn} color='primary' variant="contained" style={btnstyle} fullWidth>Sign in</Button>
<Typography > Don't Have Account ?
<NavLink to="Signup">
<span style={{marginLeft:"4px"}}>Singup</span>
</NavLink>
</Typography>
</Paper>
</Grid>
)
}
export default Login
Now Make Home Page ( src/Home.js)
import React from 'react'
import { Grid,Paper, Avatar,Box,Link, TextField, Button, Typography,Link as Nv } from '@material-ui/core'
import { useHistory, useParams } from "react-router-dom";
const Home=()=>{
const paperStyle={padding :20,height:'70vh',width:280, margin:"20px auto"}
const avatarStyle={backgroundColor:'#3370bd'}
const btnstyle={margin:'8px 0'}
const {users} = useParams();
let history = useHistory();
const usersss = localStorage.getItem('users');
const logout = () =>
{
localStorage.removeItem("users")
history.push("/");
}
return(
<div className="">
<Grid>
<div style={{ float:"right",marginRight:"50px"}}>
<Button type='submit' onClick={logout} color='primary' justifyContent="flex-end" variant="contained" style={btnstyle} fullWidth>Logout</Button>
</div>
</Grid>
<h4 style={{textAlign:"left",marginLeft:"10px"}}>Welcome To Home : <span style={{color:"blue"}}>{usersss}</span></h4>
<h2 style={{color:"green"}}>Welcome To Home Page </h2>
<p>React (also known as React.js or ReactJS) is an open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by ...
<p>React · Declarative. React makes it painless to create interactive UIs. · Component-Based. Build encapsulated components that manage their own state, then ...</p>
<Grid container direction="row" justify="center" alignItems="center">
<Grid item xs={4}>
<Typography gutterBottom variant="subtitle1">
Standard license
</Typography>
<Typography variant="body2" gutterBottom>
Full resolution 1920x1080 • JPEG
</Typography>
<Typography variant="body2" color="textSecondary">
ID: 1030114
</Typography>
</Grid>
<Grid item xs={4}>
<Typography gutterBottom variant="subtitle1">
Standard license
</Typography>
<Typography variant="body2" gutterBottom>
Full resolution 1920x1080 • JPEG
</Typography>
<Typography variant="body2" color="textSecondary">
ID: 1030114
</Typography>
</Grid>
<Grid item xs={4}>
<Typography gutterBottom variant="subtitle1">
Standard license
</Typography>
<Typography variant="body2" gutterBottom>
Full resolution 1920x1080 • JPEG
</Typography>
<Typography variant="body2" color="textSecondary">
ID: 1030114
</Typography>
</Grid>
</Grid>
</p>
</div>
)
}
export default Home
Now Call all components in App.js file .
App.js
import './App.css';
import { BrowserRouter as Router, Route,Switch,withRouter} from "react-router-dom";
import Login from "./Login";
import Signup from "./Signup";
import Home from "./Home";
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/Home" component={Home} />
<Route exact path="/" component={Login} />
<Route exact path="/Signup" component={Signup} />
</Switch>
</div>
</Router>
);
}
export default App;
I am using PORT 3000 for React and PORT 8000 For Laravel
Run React using npm start ….It will run on http://localhost:3000/
Subscribe to My Programming YouTube Channel Before Downloading the code :
Download the Source Code from Here : Login in React
Read More Articles
PHP CRUD Application using OOP and MYSQL
Live Search with React and NodeJS
CRUD Operation Using React & Nodejs
Wonderful Content bhai 🎈🙏🙏.
Please don’t stop teaching us ❤️
Thank You
Nicely done. But it would be much better if you use protected API’s with tokens.
Well, Said but Freshers ( in API ) cant understand complex code dear…That’s Why i made it Simple
After the successful login, When I refresh the home page the 404 | Not Found page is displaying. why is that?
Please send me the screen short of the error …With (Please make sure You Network Tab is on ) I want to see Request by REACT to Laravel
Mail me : dysengg252@gmail.com