Have you faced difficulties in creating a custom Laravel login and registration system? If yes, then please follow this post very carefully. Today, I am going to show you how you can create a custom Laravel 6 login and registration. In this procedure, I am not going to use the Laravel predefined user Auth. The predefined user auth in Laravel provides the user registration, login, logout with the session. I have already shown you how to create user registration with default auth in Laravel 6. But, today I will show, how you can create these all functionalities inside Laravel 6.
Prerequisites
For creating a new Laravel 6 project, your system must be ready with the following-
- PHP version >=7.3.9
- MySQL (version > 5)
- Apache/Nginx Server
So, once you are ready with the above, let’s begin to have for a new project.
Create a New Laravel Login and Registration Project
I am going to create a new project in Laravel 6 for implementing the Laravel user login and registration. This will contain the functionalities of user registration, login, and logout using the session. The login and logout features will be managed by the Laravel session helper. So, just open the terminal or command window and enter the below command.
composer create-project --prefer-dist laravel/laravel laravel6-registration
This will create a new folder with the name laravel6-registration. Inside the project folder, it will install the Laravel 6 files and libraries. It will take some time depending on your system to install the necessary library.
After the successful creating of the project, let’s move to the database section.
RESTful APIs in Laravel 6 with Passport Authentication
Create a New Database
Open the MySQL command line or phpMyAdmin or MySQL WorkBench. Now, create a new database there.
CREATE DATABASE laravel6_registration;
Once you have created the database in MySQL. Let’s have to configure it in Laravel 6. Open the .env file of the project and replace your database details with the below details.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_user_registration;
DB_USERNAME=root
DB_PASSWORD=root
How to Use AJAX in Laravel 6 with ToDo Application
User Model in Laravel Login and Registration
In the Laravel 6 project, you will have already a model for the User. This model is default with the project setup. Also, the project will have a user migration file that contains the database schema. So, just make some changes in the existing schema (create_users_table.php) file.
The create_users_table.php file has located inside the database/migrations. So, just replace the below schema with yours.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('phone');
$table->rememberToken();
$table->timestamps();
});
}
After setup, the migration file just migrate the tables in the database. The migration process will create the tables in the database automatically.
After the migration of the database, you can check the schema of the tables. Here, we need only the users table because we are going to work on the User model only.
After the table migration, we’ll have to define the fields that would be going to insert into the database.
Laravel 6 REST API For ToDo Application with Passport Auth
Set Mass Assignment For User Model
In the next step, you will have to define the mass assignment for the User model. In Laravel, you can set the fillable data using the mass assignment approach. So, just replace the snippet of the User.php file with the below code.
// User.php
<?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',
];
}
After the mass assignment in the model, we’ll move on for the functionality of the user registration, login, and logout.
How to Send Email in Laravel 6 Via Gmail Using SMTP
Create Controller For Laravel User Login and Registration
For managing the user’s functionalities, we’ll have to create a controller. In the terminal or command prompt enter the below command. This will create a controller with the name UserController.
php artisan make:controller UserController
In the project directory, now, you will have the UserController.php file. So, just add the below snippet there.
// UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class UserController extends Controller {
// -------------------- [ user registration view ] -------------
public function index() {
return view('registration');
}
// --------------------- [ Register user ] ----------------------
public function userPostRegistration(Request $request) {
// validate form fields
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'phone' => 'required|max:10'
]);
$input = $request->all();
// if validation success then create an input array
$inputArray = array(
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'full_name' => $request->first_name . " ". $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
);
// register user
$user = User::create($inputArray);
// if registration success then return with success message
if(!is_null($user)) {
return back()->with('success', 'You have registered successfully.');
}
// else return with error message
else {
return back()->with('error', 'Whoops! some error encountered. Please try again.');
}
}
// -------------------- [ User login view ] -----------------------
public function userLoginIndex() {
return view('login');
}
// --------------------- [ User login ] ---------------------
public function userPostLogin(Request $request) {
$request->validate([
"email" => "required|email",
"password" => "required|min:6"
]);
$userCredentials = $request->only('email', 'password');
// check user using auth function
if (Auth::attempt($userCredentials)) {
return redirect()->intended('dashboard');
}
else {
return back()->with('error', 'Whoops! invalid username or password.');
}
}
// ------------------ [ User Dashboard Section ] ---------------------
public function dashboard() {
// check if user logged in
if(Auth::check()) {
return view('dashboard');
}
return redirect::to("user-login")->withSuccess('Oopps! You do not have access');
}
// ------------------- [ User logout function ] ----------------------
public function logout(Request $request ) {
$request->session()->flush();
Auth::logout();
return Redirect('user-login');
}
}
In the above controller file, I have created various functions. In the first function, I have loaded the user registration view. Then next (userPostRegistration) function has created to validate the form fields. After the successful validation, the user’s record will be inserted into the database.
The userLoginIndex() function returns the user login view. In the userPostLogin() function, at very first, the input fields will be validated. Then using the Auth, the user will be validated. Once, the user credentials are validated, the session will be created. Session in Laravel 6 stores any kind of small data that can be used further from anywhere (within a project).
Now, we’ll require the routes for the above functions. So, in the next step, just create routes for the above functions.
How to Implement Yajra Datatables in Laravel 6
Routes
In Laravel (MVC), without defining routes, you cannot access any function from the controller directly. So, for performing the user’s related functionalities add the below routes in the web.php file.
Route::get('user-registration', 'UserController@index');
Route::post('user-store', 'UserController@userPostRegistration');
Route::get('user-login', 'UserController@userLoginIndex');
Route::post('login', 'UserController@userPostLogin');
Route::get('dashboard', 'UserController@dashboard');
Route::get('logout', 'UserController@logout');
Now, according to the project, we’ll have to create the views (UI) in which the user will interact.
Create Views
So, I am going to create the following views for this project.
- master.blade.php
- registration.blade.php
- login.blade.php
- dashboard.blade.php
In the master.blade.php file, I will add the Bootstrap CDN. This will be a global file that can be used in all the views.
<!-- master.blade.php -->
<!doctype html>
<html lang="en">
<head>
<title> User Custom Registration and Login with Session </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
@yield('content')
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
How to Upload Files and Images in Laravel 6 with Validation
User Registration Blade
<!-- registration.blade.php -->
@extends('master')
@section('content')
<div class="container mt-3">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="post" action=" {{ url('user-store') }} ">
<div class="card shadow mb-4">
<div class="car-header bg-success pt-2">
<div class="card-title font-weight-bold text-white text-center"> Laravel 6 User Registration </div>
</div>
<div class="card-body">
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="form-group">
<label for="first_name"> First Name </label>
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="Enter First Name" value="{{ old('first_name') }}"/>
{!! $errors->first('first_name', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group">
<label for="last_name"> Last Name </label>
<input type="text" name="last_name" id="last_name" class="form-control" placeholder="Enter Last Name" value="{{ old('last_name') }}"/>
{!! $errors->first('last_name', '<small class="text-danger">:message </small>') !!}
</div>
<div class="form-group">
<label for="email"> E-mail </label>
<input type="text" name="email" id="email" class="form-control" placeholder="Enter E-mail" value="{{ old('email') }}"/>
{!! $errors->first('email', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group">
<label for="password"> Password </label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter Password" value="{{ old('password') }}"/>
{!! $errors->first('password', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group">
<label for="confirm_password"> Confirm Password </label>
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" value="{{ old('confirm_password') }}">
{!! $errors->first('confirm_password', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group">
<label for="phone"> Phone </label>
<input type="phone" name="phone" id="phone" class="form-control" placeholder="Enter Phone" value="{{ old('phone') }}">
{!! $errors->first('phone', '<small class="text-danger">:message</small>') !!}
</div>
</div>
<div class="card-footer d-inline-block">
<button type="submit" class="btn btn-success"> Register </button>
<p class="float-right mt-2"> Already have an account? <a href="{{ url('user-login')}}" class="text-success"> Login </a> </p>
</div>
@csrf
</div>
</form>
</div>
</div>
</div>
@endsection
Save and run the Laravel 6 login and registration project to see the registration form. According to the above-listed routes, hit the below URL in the browser.
http://localhost:8000/user-registration
The user registration form will be showing like this.
In the next step, we’ll have to validate the form fields. So, the user cannot register the account without filling up the required details. When you’ll try to submit the form without filling the form it will show you the validation errors.
Once, you will fill all the required details and register, the registration will be completed successfully. Here, you can see in the result as shown below.
In the table, you can check for the records. Here, I have registered an account that is showing below.
User Login Blade
<!-- login.blade.php -->
@extends('master')
@section('content')
<div class="container mt-3">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="post" action="{{ url('login') }}">
<div class="card shadow">
<div class="car-header bg-success pt-2">
<div class="card-title font-weight-bold text-white text-center"> User Login </div>
</div>
<div class="card-body">
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="form-group">
<label for="email"> E-mail </label>
<input type="text" name="email" id="email" class="form-control" placeholder="Enter E-mail" value="{{ old('email') }}"/>
{!! $errors->first('email', '<small class="text-danger">:message</small>') !!}
</div>
<div class="form-group">
<label for="password"> Password </label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter Password" value="{{ old('password') }}"/>
{!! $errors->first('password', '<small class="text-danger">:message</small>') !!}
</div>
</div>
<div class="card-footer d-inline-block">
<button type="submit" class="btn btn-success"> Login </button>
<p class="float-right mt-2"> Don't have an account? <a href="{{ url('user-registration')}}" class="text-success"> Register </a> </p>
</div>
@csrf
</div>
</form>
</div>
</div>
</div>
@endsection
In the browser, hit the user login URL.
http://localhost:8000/user-login
The user login view will be looking like this.
How to Implement Pagination in Laravel 6 with Example
Similarly, I have added the validation for email and password here. So, that the blank fields will not be submitted.
Enter the correct email and password.
After a successful login, a session will be created. Also, you will be redirected to the dashboard page.
@extends('master')
@section('content')
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">Laravel 6 User Registration and Login</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarColor01">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link text-white"> Welcome: {{ ucfirst(Auth()->user()->first_name) }} </a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url('logout') }}"> Logout </a>
</li>
</ul>
</div>
</nav>
@endsection
So, add the above snippet in dashboard.blade.php.
In the dashboard section, the user’s first name has printed using the session. In the right corner, there is an option for logout. When you will logout from the dashboard, it will redirect you to the login page.
If you try to navigate back to the dashboard page and after refreshing the page, it will redirect you again to the login page. Here, you can see the access error that has been occurred after the logout. This is done because of the session in Laravel 6. When you logged out, the session has been destroyed. So every time when you will log in, a new session will be created.
Similarly, when you will logout, the session will be flushed out.
If you try with an incorrect email or password then it will not allow you to login.
Conclusion
Ultimately, we have created a Laravel user login and registration system. Also, we have learned how to create and destroy the session in Laravel 6. Using a session in Laravel 6, you can manage the user login details. Using auth the Laravel automatically validates the correct user. When validation completes a session will create. Using the session we have stored the user’s information. Hopefully, it will be a helpful demo for you. You can implement this approach in your application. If you feel any difficulty in this post, then please let me know. I will get back to you as soon as possible.
Leave a Reply