45 views
asked in Laravel by
Multi Auth for User and Admin Using Guards in Laravel 11 - part 2

1 Answer

answered by

inchirags@gmail.com  Chirag's Laravel Tutorial https://www.chirags.in
*********************************************************************************************
Multi Auth for User and Admin Using Guards in Laravel 11- Part2
*********************************************************************************************

https://youtu.be/d8MCmeAJvcA
Tutorial Link part 1:
https://www.chirags.in/index.php/147/multi-auth-for-user-and-admin-using-guards-in-laravel-11-part1
-------------------------------------------------------------------------------------------------------------------------------------

Step 8: Write the codes in admins blade pages

//admin_home.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dashboard | Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <h2>Admin Dashboard</h2>
            <div class="col-md-5">
                @if(Session::has('success'))
                    <div class="alert alert-success">{{ Session::get('success') }}</div>
                @endif
                <table class="table table-responsive">
                    <thead>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Action</th>
                    </thead>
                    <tbody>
                        <tr>
                            <td>{{ Auth::guard('admin')->user()->name }}</td>
                            <td>{{ Auth::guard('admin')->user()->email }}</td>
                            <td>
                                {{--  <a href="{{ url('admin/logout') }}" > Logout </a>
                                <a href="{{ route('admin.logout') }}" onClick="event.preventDefault();document.getElementById('logout-form')" > Logout </a>  --}}
                                <form name="logout-form" action="{{ url('admin/logout') }}" method="POST" >
                                    @csrf
                                    <button type="submit" class="btn btn-primary">Logout</button>
                                </form>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>

//admin_login.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <h2>Admin Login page</h2>
            <div class="col-md-5">
                @if(Session::has('success'))
                    <div class="alert alert-success">{{ Session::get('success') }}</div>
                @endif
                @if(Session::has('error'))
                    <div class="alert alert-danger">{{ Session::get('error') }}</div>
                @endif
                <form action="{{ url('admin/dologin') }}" method="POST">
                    @csrf

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

                    <button type="submit" class="btn btn-primary">Submit</button>
                    New User <a href="{{ url('admin/register') }}">Admin Register Now</a>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>

//admin_register.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Registration</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <h2>Admin Registration page</h2>
            <div class="col-md-5">
                @if(Session::has('success'))
                    <div class="alert alert-success">{{ Session::get('success') }}</div>
                @endif
                @if(Session::has('error'))
                    <div class="alert alert-danger">{{ Session::get('error') }}</div>
                @endif
                <form action="{{ route('admin.create') }}" method="POST">
                    @csrf
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter full name" value="{{ old('name') }}">
                        <sapn class="text-danger">@error('name'){{ $message }}@enderror</sapn>
                      </div>
                    <div class="form-group">
                      <label for="email">Email address</label>
                      <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" value="{{ old('email') }}">
                      <sapn class="text-danger">@error('email'){{ $message }}@enderror</sapn>
                    </div>
                    <div class="form-group">
                      <label for="password">Password</label>
                      <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                      <sapn class="text-danger">@error('password'){{ $message }}@enderror</sapn>
                    </div>
                    <div class="form-group">
                        <label for="confirm_password">Confirm Password</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm Password">
                        <sapn class="text-danger">@error('confirm_password'){{ $message }}@enderror</sapn>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                    Already Registered <a href="{{ route('admin.login') }}">Admin Login</a>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>

Step 9: Create UserController Methods.

//app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Hash;
use Auth;

class UserController extends Controller
{
    public function register()
    {
        return view('user.user_register');
    }
    public function create(Request $request)
    {
        //dd($request);
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|max:15',
            'confirm_password' => 'required|same:password'
        ],[
            'confirm_password.required' => 'The confirm password field is required.',
            'confirm_password.same' => 'The confirm password and password must be same.',
        ]);
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $data = $user->save();
        if($data) {
            return redirect()->back()->with('success','You have registered successfully.');
        } else {
            return redirect()->back()->with('error','Your registration failed.');
        }
    }
    public function dologin(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:8|max:15',
        ]);
        $check = $request->only('email','password');
        if(Auth::guard('web')->attempt($check)) {
            return redirect('user/home')->with('success','Welcome to dashboard.');
        } else {
            return redirect()->back()->with('error','Login failed.');
        }
    }
    public function logout(Request $request)
    {
        Auth::guard('web')->logout();
        return redirect('user/login');
    }

}

Step 10: Create AdminController Methods.

//app/Http/Controllers/AdminController.php

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Product;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Hash;
use Session;
use Mail;
use DB;
use File;

class AdminController extends Controller
{
    public function register()
    {
        return view('admin.admin_register');
    }
    public function create(Request $request)
    {
        //dd($request);
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:admins,email',
            'password' => 'required|min:8|max:15',
            'confirm_password' => 'required|same:password'
        ],[
            'confirm_password.required' => 'The confirm password field is required.',
            'confirm_password.same' => 'The confirm password and password must be same.',
        ]);
        $user = new Admin();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $data = $user->save();
        if($data) {
            return redirect()->back()->with('success','You have registered successfully.');
        } else {
            return redirect()->back()->with('error','Your registration failed.');
        }
    }
    public function dologin(Request $request)
    {
        //dd($request->all());
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:6|max:15',
        ]);
        $credentials = $request->only('email','password');
        if(Auth::guard('admin')->attempt($credentials)) {
            return redirect()->route('admin.home')->with('success','Welcome to admin dashboard.');
        } else {
            return redirect()->back()->with('error','Admin Login failed.');
        }
    }
}

Step 11: Modify in Admin model page.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 12: Modify in migration file page.

//database/migrations/......create_admins_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('admins');
    }
};

Step 13: Create route in Web.php page.

//routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\User\UserController;
use App\Http\Controllers\Admin\AdminController;

Route::prefix('user')->name('user.')->group(function(){
    Route::middleware(['guest:web'])->group(function () {
        Route::view('/login','user.user_login')->name('login');
        Route::get('/register',[UserController::class,'register'])->name('register');
        Route::post('/create',[UserController::class,'create'])->name('create');
        Route::post('/dologin',[UserController::class,'dologin'])->name('dologin');

    });
    Route::middleware(['auth:web'])->group(function () {
        Route::view('/home','user.user_home')->name('home');
        Route::post('/logout',[UserController::class,'logout'])->name('logout');
    });
});

Route::prefix('admin')->name('admin.')->group(function(){
    Route::middleware(['guest:admin'])->group(function () {
        Route::view('/login','admin.admin_login')->name('login');
        Route::get('/register',[AdminController::class,'register'])->name('register');
        Route::post('/create',[AdminController::class,'create'])->name('create');
        Route::post('/dologin',[AdminController::class,'dologin'])->name('dologin');
    });
    Route::middleware(['auth:admin'])->group(function () {
        Route::view('/home','admin.admin_home')->name('home');
    });
});

Step 14: migrate the database.

php artisan migrate

Step 15: Subsequently, launch the Laravel application.

php artisan serve

Step 16: Access the user side pages.

http://127.0.0.1:8000/user/login
http://127.0.0.1:8000/user/register

after login

http://127.0.0.1:8000/user/home

Step 17: Access the admin side pages.

http://127.0.0.1:8000/admin/login
http://127.0.0.1:8000/admin/register

after login

http://127.0.0.1:8000/admin/home

For any doubts and query, please write on YouTube video comments section.

Note : Flow the Process shown in video.

Please, Subscribe and like for more videos:
https://www.youtube.com/@chiragstutorial
Don't forget to, Follow, Like, Share &, Comment

Thanks & Regards,
Chitt Ranjan Mahto "Chirag"

_____________________________________________________________________
Note: All scripts used in this demo will be available in our website.
Link will be available in description.

#chirags
#chiragstutorial
#chiragslaraveltutorial
#chiragslaraveltutorials
#laraveltutorial
#laravel11
#laravelcourse
#installlaravel
#laravel_tutorial
#laravelphp
#chiragdbatutorial
#chiragsdbatutorial
#chriagstutorial
#laravel11multiauth
#laravelmultiauth

https://youtu.be/d8MCmeAJvcA

Most popular tags

postgresql laravel replication ha postgresql laravel-10 mongodb ubuntu 24.04 lts mongodb database mongodb tutorial streaming-replication mysql laravel-11 database laravel postgresql backup database mysql php technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python user and admin registration user and admin login multiauth zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux laravel login register logout replica php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 gaurds laravel 11 guards mongodb sharding metabase business analytics metabase ubuntu 24.04 koha 24.05 postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5 access configuration in postgresql hba configuration laravel multiple database configuration state city country dropdown live photo upload webcam captcha in laravel
...