Laravel 10 Authentication (Registration Login Logout with Middleware)

PLAB Studio
4 min readJan 11, 2024

--

Creating an authentication system by connecting to a database create tables with migration, create registration, login and logout views. Write controllers, create routes, and install middleware tools to monitor logged-in sessions.

Step 1 : Install Laravel project.

composer create-project laravel/laravel example-authenctication

Step 2 : Connect DB and make model.

First, you need to delete the model and migration files before rebuilding them with the command:

php artisan make:model User -m

Add the required columns to the user table.

    public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique;
$table->string('password');
$table->timestamps();
});
}

After that use the command.

php artisan migrate

Make additional edits to the user model.

class User extends Model
{
use HasFactory;
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}

Step 3 : Make views.

Create an registration page. views/auth/registration.blade.php

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Registration</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-col-md-offset-4">
<h2>Registration</h2>
<form action="{{route('register-user')}}" method="post" enctype="multipart/form-data">
@csrf
@if (Session::has('success'))
<div class="alert alert-success">
{{Session::get('success')}}
</div>
@endif
@if (Session::has('fail'))
<div class="alert alert-danger">
{{Session::get('fail')}}
</div>
@endif
<div class="form-group">
<label for="name">Full Name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger">
@error('name')
{{$message}}
@enderror
</span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control">
<span class="text-danger">
@error('email')
{{$message}}
@enderror
</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
<span class="text-danger">
@error('password')
{{$message}}
@enderror
</span>
</div>

<br>
<div class="form-group">
<button type="submit" class="btn btn-block btn-success">Registration</button>
</div>
<br>
<a href="login">Login Here!</a>
</form>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</div>

</body>
</html>

Create an registration page. views/auth/login.blade.php

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-col-md-offset-4">
<h2>Login</h2>
<form action="{{route('login-user')}}" method="post" enctype="multipart/form-data">
@csrf
@if (Session::has('success'))
<div class="alert alert-success">
{{Session::get('success')}}
</div>
@endif
@if (Session::has('fail'))
<div class="alert alert-danger">
{{Session::get('fail')}}
</div>
@endif

<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control">
<span class="text-danger">
@error('email')
{{$message}}
@enderror
</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
<span class="text-danger">
@error('password')
{{$message}}
@enderror
</span>
</div>

<br>
<div class="form-group">
<button type="submit" class="btn btn-block btn-success">Login</button>
</div>
<br>
<a href="registration">Registration</a>
</form>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</div>

</body>
</html>

Create an registration page. views/dashboard.blade.php

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Dashboard</h1>
<table class="table table-striped">
<thead>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</thead>
<tbody>
<td>{{$data->name}}</td>
<td>{{$data->email}}</td>
<td><a href="logout">Logout</a></td>
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</div>
</body>
</html>
Registration screen
Login screen

Step 4 : Make authentication controller.

php artisan make:controller AuthenController
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class AuthenController extends Controller
{
//Registration
public function registration()
{
return view('auth.registration');
}
public function registerUser(Request $request)
{
$request->validate([
'name'=>'required',
'email'=>'required|email:users',
'password'=>'required|min:8|max:12'
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;

$result = $user->save();
if($result){
return back()->with('success','You have registered successfully.');
} else {
return back()->with('fail','Something wrong!');
}
}
////Login
public function login()
{
return view('auth.login');
}
public function loginUser(Request $request)
{
$request->validate([
'email'=>'required|email:users',
'password'=>'required|min:8|max:12'
]);

$user = User::where('email','=',$request->email)->first();
if($user){
if(Hash::check($request->password, $user->password)){
$request->session()->put('loginId', $user->id);
return redirect('dashboard');
} else {
return back()->with('fail','Password not match!');
}
} else {
return back()->with('fail','This email is not register.');
}
}
//// Dashboard
public function dashboard()
{
// return "Welcome to your dashabord.";
$data = array();
if(Session::has('loginId')){
$data = User::where('id','=',Session::get('loginId'))->first();
}
return view('dashboard',compact('data'));
}
///Logout
public function logout()
{
$data = array();
if(Session::has('loginId')){
Session::pull('loginId');
return redirect('login');
}
}
}

Step 5 : Middleware.

php artisan make:middleware AlreadyLoggedIn
php artisan make:middleware AuthCheck

Define the details required for middleware implementation.
Kernel.php

    protected $routeMiddleware = [
'isLoggedIn' => \App\Http\Middleware\AuthCheck::class,
'alreadyLoggedIn' => \App\Http\Middleware\AlreadyLoggedIn::class,
];

AlreadyLoggedIn.php
Add additional details as follows.

    public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId') && (url('login') == $request->url() || url('registration') == $request->url())){
return back();
}
return $next($request);
}

AuthCheck.php
Add additional details as follows.

    public function handle(Request $request, Closure $next)
{
if(!Session()->has('loginId')){
return redirect('login')->with('fail','You have to login first.');
}
return $next($request);
}

Step 6 : Routes.

Define the part that executes the middleware when routing.

use App\Http\Controllers\AuthenController;

Route::controller(AuthenController::class)->group(function(){
Route::get('/registration','registration')->middleware('alreadyLoggedIn');
Route::post('/registration-user','registerUser')->name('register-user');
Route::get('/login','login')->middleware('alreadyLoggedIn');
Route::post('/login-user','loginUser')->name('login-user');
Route::get('/dashboard','dashboard')->middleware('isLoggedIn');
Route::get('/logout','logout');
});

Test.

php artisan serve

--

--

PLAB Studio

คนประสบความสำเร็จมักมองหาโอกาส คนล้มเหลวมองทุกอย่างเป็นอุปสรรค ลงมือทำแม้จะล้มเหลว จงเรียนรู้กับมันเพื่อสร้างโอกาสให้ตนเองถึงเป้าหมาย