Registration and Login is a core functionality of any application. If you are creating an application that will have certain access for certain users. Then definitely you will have to create the login and sign up procedure before diving into the application. So, you can say that the Login and sign up is the initial step for any application. So, today, in this post, I will be creating a React Login and Registration app using the Laravel 7 API. Yes, we will be using the back-end as the Laravel 7 that will be managed using the RESTful APIs. In our last tutorial of React, we had seen how to integrate the APIs in React application. That was the basic demonstration through a CRUD application. But, in this React login form and sign up tutorial, we will be doing some advanced procedure. So, let’s start without wasting more time.
Firstly, I will start with the APIs part that will be creating using the Laravel 7 with MySQL database.
Prerequisites
For creating a Laravel 7 project, I assume that your system configuration is ready with the mentioned as below.
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- Composer
- Postman
Now, let’s start by creating the Laravel project for the React Login and Registration API.
Create a New Project in Laravel 7 For React Login and Registration API
For creating a new project in Laravel, we will use the composer dependency manager. Hence, open the command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel login-api
It will take a couple of minutes to create and setup the new project in your system. So, please wait for the completion.
How to Use Http Client For Request Handling in Laravel 7
Create and Configure Database
I am using MySQL command line, so will be creating a new database there.
CREATE DATABASE laravel7_login_api
After creating the database, we will configure the database credentials inside the project. Laravel contains the a global environment file for these type of configuration. Inside the root of your project, you will find the .env file. Now, open the file and replace the database details with yours.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel7_login_api
DB_USERNAME=root
DB_PASSWORD=root
Now, your project is ready to sync with the MySQL database. So, in the next step, we will create the Model and Migration file.
We are going to implement the React login and sign up using the Laravel RESTful API. Hence, we will be working on the User module for this project. Therefore, we will require to create a model and migration for the user.
Create Model and Migration For Users
Laravel project comes with a default Model and migration for the Users. So, at the moment we can use this model and migration for the Users. Here, we will be doing the same, but we will make changes in the migration file. So, let’s do it by adding the schema for the users table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("first_name")->nullable();
$table->string("last_name")->nullable();
$table->string("full_name")->nullable();
$table->string("email")->unique();
$table->string("password");
$table->string("phone")->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Add the above schema for the Users. Here, I am going to create a React login and sign up functionality with some basic attributes of the Users. You can add more fields by adding the schema in the above migration file.
Create a Todo App in React Using Laravel 8 RESTful APIs
Migrate Users Table Schema
Now, we will migrate the users table so that the defined schema will be generated in the database.
php artisan migrate
The above command will migrate all the schema inside the database.
Add Fillable Data in User Model
Inside the User model, we will have to add the fillable data. The fillable data will define the database table fields which will gonna manage through the model.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'full_name', 'email', 'password', 'phone'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
How to Implement Yajra DataTable in Laravel 7
Create a Controller in Laravel 7
For implementing the React login and signup functionality using the API, we will have to create a controller. Here, I will be creating a controller named UserController using the artisan command.
php artisan make:controller UserController
The above command will create a controller inside the app/Http/Controllers folder.
How to Implement Google Charts in Laravel 7
After creating the controller, we will create the functionality for the React login page.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
private $status_code = 200;
public function userSignUp(Request $request) {
$validator = Validator::make($request->all(), [
"name" => "required",
"email" => "required|email",
"password" => "required",
"phone" => "required"
]);
if($validator->fails()) {
return response()->json(["status" => "failed", "message" => "validation_error", "errors" => $validator->errors()]);
}
$name = $request->name;
$name = explode(" ", $name);
$first_name = $name[0];
$last_name = "";
if(isset($name[1])) {
$last_name = $name[1];
}
$userDataArray = array(
"first_name" => $first_name,
"last_name" => $last_name,
"full_name" => $request->name,
"email" => $request->email,
"password" => md5($request->password),
"phone" => $request->phone
);
$user_status = User::where("email", $request->email)->first();
if(!is_null($user_status)) {
return response()->json(["status" => "failed", "success" => false, "message" => "Whoops! email already registered"]);
}
$user = User::create($userDataArray);
if(!is_null($user)) {
return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registration completed successfully", "data" => $user]);
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "failed to register"]);
}
}
// ------------ [ User Login ] -------------------
public function userLogin(Request $request) {
$validator = Validator::make($request->all(),
[
"email" => "required|email",
"password" => "required"
]
);
if($validator->fails()) {
return response()->json(["status" => "failed", "validation_error" => $validator->errors()]);
}
// check if entered email exists in db
$email_status = User::where("email", $request->email)->first();
// if email exists then we will check password for the same email
if(!is_null($email_status)) {
$password_status = User::where("email", $request->email)->where("password", md5($request->password))->first();
// if password is correct
if(!is_null($password_status)) {
$user = $this->userDetail($request->email);
return response()->json(["status" => $this->status_code, "success" => true, "message" => "You have logged in successfully", "data" => $user]);
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "Unable to login. Incorrect password."]);
}
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "Unable to login. Email doesn't exist."]);
}
}
// ------------------ [ User Detail ] ---------------------
public function userDetail($email) {
$user = array();
if($email != "") {
$user = User::where("email", $email)->first();
return $user;
}
}
}
How to Send Email Using Gmail SMTP in Laravel 7
Create Routes
After creating the functionalities of login and sign up we will create the routes. Here, we are creating the API, hence we will have to put the routes inside the api.php file.
Route::post("user-signup", "UserController@userSignUp");
Route::post("user-login", "UserController@userLogin");
Route::get("user/{email}", "UserController@userDetail");
Run Application To Test API
After creating the routes, let’s serve the project. Here, the default port of the application is 8000.
So, for the user sign up the endpoint will be –
http://localhost:8000/api/user-signup
Request Type : POST
So, for testing the API, I will be using the Postman. In the postman, put the form fields in Body->form-data.
After hitting the API, you will get the response as below.
In the user sign up, I have used the form validation. Hence, if you keep empty the fields, it will return the validation errors.
Similarly, run the user login API. For the user login the endpoint will be-
http://localhost:8000/api/user-login
Request Type : POST
Now, put the fields as showing below. After putting the fields hit the API.
If the email and password is correct, it will return the success response with status 200. Here, the login API has been executed.
If the validation fails, it will return the validation errors as showing below.
So, API is ready to implement the React login sign up functionality. Hence, move to the front-end part React login page.
Create React Login App
For creating a new React application you will require the Node.js installed in your system.
Let’s Create Registration Application in Reactjs.
Create the React Registration App
Open the terminal or command prompt and hit the below command to create a registration app
npx create-react-app registration-app
The above command initiate to create the registration-app
It will take a few minutes to create the react registration-app. Then, go to registration-app by using below command
cd registration-app
Now , run the app using the command
npm start
Now, the app will be running on the default port localhost:3000.
Create a Todo App in React Using Laravel 8 RESTful APIs
Install Bootstrap and Reactstrap in Reactjs Registration App
For the UI part, I will be using the Bootstrap. This will make ease for creating the layouts with the predefined classes. Hence, for installing the Bootstrap, simply hit the below command in the terminal or command prompt.
npm install bootstrap reactstrap
The above command will add the Bootstrap CSS and JS file globally inside the Reactjs Registration application.
After completing the installation, let’s import the Bootstrap CSS in our application. Basically, we will be including the globally that’s why we will import it in the src/index.js file of our application.
import 'bootstrap/dist/css/bootstrap.min.css';
For API call we will be using the Axios library for handling the HTTP requests.
Install Axios Library in React Login App
install axios
npm install --save axios
Install React Router Dom
For Routing, install React Router DOM by following command.
npm install --save react-router-dom
Create Component in Reactjs Registration App
Create a folder named components inside that create the files. see below picture.
Now all the setup has been done let’s start to write our code.
Import Components and Router in App.js
In App.js file import the Signup, Sign in, and Home file. We will also import the router for routing. This App.js file acts as a container to switch between SignUp.js, SignIn.js, and Home.js components respectively.
// App.js file
import React, { Component } from "react";
import "./App.css";
import Signup from "./components/signUp/Signup";
import Signin from "./components/SignIn/Signin";
import Home from "./components/Home/Home";
import { BrowserRouter as Router, Route, NavLink } from "react-router-dom";
export default class App extends Component {
render() {
let navLink = (
<div className="Tab">
<NavLink to="/sign-in" activeClassName="activeLink" className="signIn">
Sign In
</NavLink>
<NavLink exact to="/" activeClassName="activeLink" className="signUp">
Sign Up
</NavLink>
</div>
);
const login = localStorage.getItem("isLoggedIn");
return (
<div className="App">
{login ? (
<Router>
<Route exact path="/" component={Signup}></Route>
<Route path="/sign-in" component={Signin}></Route>
<Route path="/home" component={Home}></Route>
</Router>
) : (
<Router>
{navLink}
<Route exact path="/" component={Signup}></Route>
<Route path="/sign-in" component={Signin}></Route>
<Route path="/home" component={Home}></Route>
</Router>
)}
</div>
);
}
}
//App.css file
.App {
width:40%;
margin :5% 0 0 30%;
}
Create Signup component
We will work on user sign up and login process. Hence, firstly, we will require creating a component for implementing the functionality of User Sign Up. Therefore, create a component and name it Signup.js. Now, add the below snippet there.
import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input } from "reactstrap";
import axios from "axios";
import "./signup.css";
import { Link } from "react-router-dom";
export default class Signup extends Component {
userData;
constructor(props) {
super(props);
this.state = {
signupData: {
name: "",
email: "",
phone: "",
password: "",
isLoading: "",
},
msg: "",
};
}
onChangehandler = (e, key) => {
const { signupData } = this.state;
signupData[e.target.name] = e.target.value;
this.setState({ signupData });
};
onSubmitHandler = (e) => {
e.preventDefault();
this.setState({ isLoading: true });
axios
.post("http://localhost:8000/api/user-signup", this.state.signupData)
.then((response) => {
this.setState({ isLoading: false });
if (response.data.status === 200) {
this.setState({
msg: response.data.message,
signupData: {
name: "",
email: "",
phone: "",
password: "",
},
});
setTimeout(() => {
this.setState({ msg: "" });
}, 2000);
}
if (response.data.status === "failed") {
this.setState({ msg: response.data.message });
setTimeout(() => {
this.setState({ msg: "" });
}, 2000);
}
});
};
render() {
const isLoading = this.state.isLoading;
return (
<div>
<Form className="containers shadow">
<FormGroup>
<Label for="name">Name</Label>
<Input
type="name"
name="name"
placeholder="Enter name"
value={this.state.signupData.name}
onChange={this.onChangehandler}
/>
</FormGroup>
<FormGroup>
<Label for="email">Email id</Label>
<Input
type="email"
name="email"
placeholder="Enter email"
value={this.state.signupData.email}
onChange={this.onChangehandler}
/>
</FormGroup>
<FormGroup>
<Label for="phone">Phone Number</Label>
<Input
type="phone"
name="phone"
placeholder="Enter phone number"
value={this.state.signupData.phone}
onChange={this.onChangehandler}
/>
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input
type="password"
name="password"
placeholder="Enter password"
value={this.state.signupData.password}
onChange={this.onChangehandler}
/>
</FormGroup>
<p className="text-white">{this.state.msg}</p>
<Button
className="text-center mb-4"
color="success"
onClick={this.onSubmitHandler}
>
Sign Up
{isLoading ? (
<span
className="spinner-border spinner-border-sm ml-5"
role="status"
aria-hidden="true"
></span>
) : (
<span></span>
)}
</Button>
<Link to="/sign-in" className="text-white ml-5">I'm already member</Link>
</Form>
</div>
);
}
}
Add CSS for Sign Up Component
For styling, I have added some basic CSS here. Actually, I am not giving much focus on the design part. So, add the CSS in the same component that is signup.css that will be accessible only for this component.
.containers {
background-color: #A2A2A1FF;
padding: 20px 40px;
color: #fff;
font-weight: 600;
box-shadow: 7px -8px 11px -5px rgba(#195190FF);
}
.Tab{
display: flex;
justify-content: space-between;
}
.signUp, .signIn{
background-color: #A2A2A1FF;
width:50%;
font-size: 22px;
color: #fff;
padding: 10px;
text-align: center;
}
.signIn:hover, .signUp:hover {
text-decoration: none;
color: #fff;
}
.activeLink{
color: #fff;
background-color: #195190FF;
}
Here, we are taking Name, Email id, Phone no, and password as inputs from the user. Then we will be storing it into their relevant defined state variables. After that, we will pass these details of the user to the backend through API on the click of the Signup button. That will be executed by the onSubmitHandler function.
Now submitting the user data to the backend. When data will be submitted successfully, it will return the response status code 200 from the API. That we have tested above in the Laravel 7 API part. So, on the basis of the API response will show the message of success and failure to the user. After that, we will clear the states. For the message, I have set the timeout() function to display the message till a specified time.
If the response of the status is failed then we will show the failure message to the user.
Create a SignIn Component
Secondly, we will create a SignIn component. In this screen, users have to enter the email address and password for Sign-in into their account. After a successful login, the user will redirect to the Home component with a welcome message. But, if the login is invalid, then it will show the error message that will return from the API response.
So, add the below code in Signin.js.
import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input } from "reactstrap";
import axios from "axios";
import { Redirect } from "react-router-dom";
export default class Signin extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
msg: "",
isLoading: false,
redirect: false,
errMsgEmail: "",
errMsgPwd: "",
errMsg: "",
};
}
onChangehandler = (e) => {
let name = e.target.name;
let value = e.target.value;
let data = {};
data[name] = value;
this.setState(data);
};
onSignInHandler = () => {
this.setState({ isLoading: true });
axios
.post("http://localhost:8000/api/user-login", {
email: this.state.email,
password: this.state.password,
})
.then((response) => {
this.setState({ isLoading: false });
if (response.data.status === 200) {
localStorage.setItem("isLoggedIn", true);
localStorage.setItem("userData", JSON.stringify(response.data.data));
this.setState({
msg: response.data.message,
redirect: true,
});
}
if (
response.data.status === "failed" &&
response.data.success === undefined
) {
this.setState({
errMsgEmail: response.data.validation_error.email,
errMsgPwd: response.data.validation_error.password,
});
setTimeout(() => {
this.setState({ errMsgEmail: "", errMsgPwd: "" });
}, 2000);
} else if (
response.data.status === "failed" &&
response.data.success === false
) {
this.setState({
errMsg: response.data.message,
});
setTimeout(() => {
this.setState({ errMsg: "" });
}, 2000);
}
})
.catch((error) => {
console.log(error);
});
};
render() {
if (this.state.redirect) {
return <Redirect to="/home" />;
}
const login = localStorage.getItem("isLoggedIn");
if (login) {
return <Redirect to="/home" />;
}
const isLoading = this.state.isLoading;
return (
<div>
<Form className="containers">
<FormGroup>
<Label for="email">Email id</Label>
<Input
type="email"
name="email"
placeholder="Enter email"
value={this.state.email}
onChange={this.onChangehandler}
/>
<span className="text-danger">{this.state.msg}</span>
<span className="text-danger">{this.state.errMsgEmail}</span>
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input
type="password"
name="password"
placeholder="Enter password"
value={this.state.password}
onChange={this.onChangehandler}
/>
<span className="text-danger">{this.state.errMsgPwd}</span>
</FormGroup>
<p className="text-danger">{this.state.errMsg}</p>
<Button
className="text-center mb-4"
color="success"
onClick={this.onSignInHandler}
>
Sign In
{isLoading ? (
<span
className="spinner-border spinner-border-sm ml-5"
role="status"
aria-hidden="true"
></span>
) : (
<span></span>
)}
</Button>
</Form>
</div>
);
}
}
Here, the form is storing email and password in relevant state variables which will change on each keystroke in onChangehandler. We will send these details to the login API. This event will be triggered after clicking on the Sign-in button. This will be executed in the onSignInHandler function.
After the successful login, the API will return the status 200. So, on the basis of the success response, we will be maintaining the login session using the local storage. Here, I will set the item as isLoggedIn user to true.
In other case, if response status is failed then will show the error message to the user. Also, the error response will be coming from the API response.
Now, we will create a final component for the redirection after the successful login.
Create Home Component
Lastly, we will create a component as Home.js that will be used to show the welcome message after the successful login of the user. So, add the below snippet there.
import React, { Component } from "react";
import { Button } from "reactstrap";
import { Redirect } from "react-router-dom";
export default class Home extends Component {
state = {
navigate: false,
};
onLogoutHandler = () => {
localStorage.clear();
this.setState({
navigate: true,
});
};
render() {
const user = JSON.parse(localStorage.getItem("userData"));
const { navigate } = this.state;
if (navigate) {
return <Redirect to="/" push={true} />;
}
return (
<div className="container border">
<h3> HomePage</h3>
<div className="row">
<div className="col-xl-9 col-sm-12 col-md-9 text-dark">
<h5> Welcome, {user.first_name} </h5> You have Logged in
successfully.
</div>
<div className="col-xl-3 col-sm-12 col-md-3">
<Button
className="btn btn-primary text-right"
onClick={this.onLogoutHandler}
>
Logout
</Button>
</div>
</div>
</div>
);
}
}
Once it is done, save and launch the application to see the result.
When the user enters the valid email id and password it will be redirected to the Home component.
After the successful login, I have redirected to the home component. In the home component, while the user is logged in the Sign In and Sign Up tabs will be disabled. This is managed by the local storage value (isLoggedIn). So, while isLoggedIn exist with true in local storage the user remains logged in.
When you will click on Logout button, it will clear the local storage value. Also, you will be redirected to the Sign In page.
Create a CRUD App in React.js Using Laravel 7 RESTful API
Conclusion
We have completed the React login and registration app using Laravel 7 API. You can implement this functionality for your real project. This was just a basic idea to manage access for users. You can make it more advance by designing it. But the logic will remain the same for all. So, I hope, this can be a helpful guide for you all. Further, you can enhance it as per your app requirements. For any query or feedback regarding this post, don’t forget to write to us in the comment section. We will get back to you as soon as possible with the solution. So, stay connect with us. Thank you. 🙂
Siddhartha says
Thank you so much for sharing this post, I was looking for the React Login Registration form with Laravel 7 API integration and I found this tutorial, it helped me a lot. Thanks a lot
Bamidele says
I would love to say a very big thank you for dis wonderful piece of code u shared with us it has really helped me in my project..
Partho says
Thank you so much for sharing this code
Tech Rebel says
is the project on github? if yes, where is the link to it?
Umesh Rana says
I have shared the repository on Github and download link is given in the post. You can download it now.
Shankara says
where did you share the Github link to download the project?
Umesh Rana says
The download link button is given at the end of the post.
Nismy says
Hi There,
You are doing a great job.
Is it possible to implement the same in Laravel 8?
Umesh Rana says
Yes, you can follow the same steps in Laravel 8 to achieve this. Nothing will change.
Shaunte Merriam says
Excellent post. I was checking constantly this blog and I’m impressed! Extremely helpful info specifically the last part 🙂 I care for such info a lot. I was looking for this certain information for a long time. Thank you and best of luck.