Here's a detailed step-by-step guide on creating a secure Laravel login system for admins and users. Please note that this is a simplified version, and you might want to adapt it based on your specific needs.
Open cmd and Enter laravel new project_name
Configure your database details in the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=
Open the existing user migration file, which is typically located at - database→migrations→YYYY_MM_DD_create_users_table.php. Add the is_admin column.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->boolean('is_admin')->default(0); // Add the is_admin column
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Run the migration to apply the changes to the database of Table :
php artisan migrate
Run the following command to generate the AuthController:
php artisan make:controller AuthController
View Name : resister.blade.php
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<form action="{{route('studentRegister')}}" method="POST">
@csrf
<div class="form-group">
<label for="name">Student Name</label>
<input value="{{old('name')}}" type="text" id="name" name="name" placeholder="Enter name" class="form-control">
@error('name')
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" value="{{old('email')}}" id="email" name="email" placeholder="Enter Email id" class="form-control">
@error('email')
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<div class="form-group">
<label for="password">Enter Password</label>
<input type="password" id="password" name="password" placeholder="Enter password" class="form-control">
@error('password')
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<div class="form-group">
<label for="password_confirmation">Re-Enter Password</label>
<input type="text" id="password_confirmation" name="password_confirmation" placeholder="Re Enter password" class="form-control">
@error("password_confirmation")
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</form>
Open the generated AuthController located at app→Http→Controllers→AuthController.php and make two function of above route:
import bellow line for AuthContoller :
Load Registration Form :
public function loadRegister()
{
return view('resister');
}
Registration Form Data submit:
public function studentRegister(Request $request)
{
// this is form validation part
$validate = $request->validate([
'name' => 'required|string|min:5',
'email' => 'required|email|max:100|unique:users',
'password' => 'required|confirmed|min:6',
'password_confirmation' => 'required'
]);
// end validation part
$data = new User(); // model for database
$data ->name = $request ->name;
$data ->email = $request ->email;
$data->password = Hash::make($request->password);
$data ->save();
return redirect()->back()->with('success','Data Save successfully');
}
Make Two view for admin and user when admin login he go to his Dashboard and when login user he go to his Dashboard . make tow route of two dashboard for lode page.
here adminDashboard view in Admin folder and studentDashboard in student folder.
// for user Dashboard view
public function StudentDashboard()
{
return view('student.studentDashboard');
}
// for admin Dashboard view
public function adminDashboard()
{
return view('admin.adminDashboard');
}
:Make Login Form :
view name - login.blade.php
Html Code :
@if(session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<form action="{{route('login')}}" method="POST">
@csrf
<div class="form-group">
<label for="email">Email</label>
<input type="email" value="{{old('email')}}" id="email" name="email" placeholder="Enter Email id" class="form-control">
@error('email')
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<div class="form-group">
<label for="password">Enter Password</label>
<input type="password" id="password" name="password" placeholder="Enter password" class="form-control">
@error('password')
<p class="text-danger">{{$message}}</p>
@enderror
</div>
<br>
<input type="submit" name="submit" value="Login" class="btn btn-primary">
</form>
import is line header section of AuthController - use Illuminate\Support\Facades\Auth;
public function loadLogin()
{
return view('login');
}
2. // Login to Dashboard code for user and admin
public function login(Request $request)
{
$request ->validate([
'email' => 'required|email',
'password' => 'required',
]);
$userCrediantials = $request->only('email', 'password');
if (Auth::attempt($userCrediantials))
{
if(Auth::user()->is_admin == 1) // for admin 1 and other admin is 0
{
return redirect('/admin/dashboard');
}
else
{
return redirect('student/dashboard');
}
}
else
{
return back()->with('error','Invalid credentials');
}
}
This Section is include of Two dashboard view page. html code is bellow :
<form action="{{ url('logout') }}" method="POST">
@csrf
<button type="submit">Logout</button>
</form>
Route::post('/logout',[AuthController::class,'logout'])->name('logout');
first import header section of AuthController - use Illuminate\Support\Facades\Session;
public function logout()
{
Session::flush();
Auth::logout();
return redirect('login'); // login page redirect
}
In Laravel, middleware is a way to filter HTTP requests entering your application. Middleware can be used to perform actions like authentication, logging, session handling, etc., before or after the request reaches your route handlers or controllers.
Run the following Artisan command to generate a new middleware: here create two middleware (1) adminMiddleware for Admin (2) AuthMIddleware for user.
This will create a file named adminMiddleware.php & AuthMIddleware.php in the app→Http→Middleware directory.
Open the adminMiddleware.php file and modify the handle method to perform the Admin login authentication:
if (Auth()->user() && Auth()->user()->is_admin == 1)
{
return $next($request);
}
return redirect('login');
Notes : this middleware in Laravel that checks if the authenticated user is an admin (is_admin == 1). If the condition is true, it allows the request to proceed; otherwise, it redirects the user to the login page.
If both conditions are true, it means the user is authenticated and has admin privileges, so the middleware allows the request to continue (return $next($request)). Otherwise, it redirects the user to the login page.
Open the AuthMIddleware.php file and modify the handle method to perform the normal user login authentication:
if (Auth()->user() && Auth()->user()->is_admin == 0)
{
return $next($request);
}
return redirect('login');
Note : a middleware in Laravel that checks if the authenticated user is not an admin (is_admin == 0). If the condition is true, it allows the request to proceed; otherwise, it redirects the user to the login page.
If both conditions are true, it means the user is authenticated and is not an admin, so the middleware allows the request to continue (return $next($request)). Otherwise, it redirects the user to the login page.
In your app→Http→Kernel.php file, add entries for your middleware in the $routeMiddleware array:
Code :
protected $routeMiddleware = [
// Other middleware entries...
'login' => \App\Http\Middleware\AuthMiddleware::class,
'checkAdmin' => \App\Http\Middleware\adminMiddleware::class,
];
Apply the middleware to your routes or controllers:
Student Dashboard Route:
Route::group(['middleware' => ['web','login']],function(){
Route::get('student/dashboard',[AuthController::class,'StudentDashboard']);
});
Note : This route make with Step 7. here include with middleware group for any body can't access this dashboard.
This route group is protected by the 'web' middleware (which includes necessary middleware for handling sessions, CSRF protection, etc.) and the 'login' middleware. It means that the user must be authenticated to access the StudentDashboard action in the AuthController.
Admin Dashboard Route:
Route::group(['middleware' => ['web','checkAdmin']],function(){
Route::get('admin/dashboard',[AuthController::class,'adminDashboard']);
});
Note : This route make with Step 7 . here include with middleware group for any body can't access this dashboard. this dashboard can access only admin.
This route group is also protected by the 'web' middleware and the 'checkAdmin' middleware. It indicates that the user must be authenticated ('web' middleware) and must pass the 'checkAdmin' middleware, which presumably checks if the user is an admin.
when user or admin login with his self Dashboard . They are can't back login page but he when logout then access login page other wise not redirect login page.
If a user tries to access the login page while already authenticated, you can redirect them to their respective dashboard instead. However, if they are not authenticated, you can show them the login page.
public function loadLogin()
{
if(Auth::user() && Auth::user()->is_admin == 1)
{
return redirect('admin/dashboard');
}
else if(Auth::user() && Auth::user()-> is_admin == 0)
{
return redirect('student/dashboard');
}
return view('login');
}
I'm a dedicated full-stack developer, entrepreneur, and the proud owner of ocec.org.in , hailing from the vibrant country of India. My passion lies in creating informative tutorials and sharing valuable tips that empower fellow artisans in their journey. With a deep-rooted love for technology, I've been an ardent enthusiast of PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, Codeigniter, and Bootstrap from their earliest days. My philosophy revolves around the values of hard work and unwavering consistency, driving me to continuously explore, create, and share my knowledge with the tech community.
helllo