Gates Tutorial in Laravel 11

 <?php


namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class UserController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            "name" => "required",
            "email" => "required|email",
            "password" => "required|confirmed",
            "age" => "required",
            "role" => "required"
        ]);

        $user = User::create($data);

        if ($user) {
            return redirect()->route("login");
        }
    }

    // public function loginPage()
    // {
    //     if (Auth::id()) {
    //         return redirect()->route("dashboard");
    //     }
    //     return view("login");
    // }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            "email" => "required|email",
            "password" => "required"
        ]);

        if (Auth::attempt($credentials)) {
            return redirect()->route("dashboard");
        }

        return redirect()->back();
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route("login");
    }

    public function dashboardPage()
    {
        return view("dashboard");

        // First way of usage of "Gate"
        // Here below, authorize() method checks whether loggedin user's role is "admin" OR not, if user is admin
        // then next line of code will be executed and if user is not admin then execution will be exit and a message
        // will show of 403 page.
        // Gate::authorize("isAdmin");
        // return view("dashboard");


        // Second way of usage of "Gate"
        // if(Gate::allows("isAdmin")) {
        //     return view("dashboard");
        // } else {
        //     return "Access Denied.";
        // }
    }

    public function ViewProfile(int $userid)
    {
        // First way of "Gate" usage
        // if (Gate::allows("view-profile", $userid)) {
        //     $user = User::findorfail($userid);
        //     return view("profile", compact("user"));
        // } else {
        //     // return redirect()->route("dashboard");
        //     abort(403);
        // }

        // we can check multiple Gate methods simultaneously using any() method
        // if we use any() method at that time we have to use array and inside array, if any one or all Gate methods
        // become true then only execution will be true and further code will execute and
        // if all Gate methods are false then only execution will be false and further code will not execute
        // if (Gate::any(["view-profile","update-post"], $userid)) {
        //     $user = User::findorfail($userid);
        //     return view("profile", compact("user"));
        // } else {
        //     // return redirect()->route("dashboard");
        //     abort(403);
        // }

        // Below condition will only true when both Gate methods false simultaneously then only condition will true
        // and execution will go ahead
        // if (Gate::none(["view-profile","update-post"], $userid)) {
        //     $user = User::findorfail($userid);
        //     return view("profile", compact("user"));
        // } else {
        //     // return redirect()->route("dashboard");
        //     abort(403);
        // }

        // Second way of "Gate" usage
        Gate::authorize("view-profile", $userid);
        $user = User::findorfail($userid);
        return view("profile", compact("user"));
    }

    public function ViewPost()
    {
        $posts = Post::where("user_id", Auth::id())->get();
        // return $post;
        return view("posts", compact("posts"));
    }

    public function UpdatePost($postid)
    {
        $post = Post::find($postid);
        $targetUser = $post->user_id;
        Gate::authorize("update-post", $targetUser);
        // $post = Post::findorfail($postid);
        return $post;
    }

    public function innerPage()
    {
        return view("inner");
    }
}
Above File is app\Http\Controllers\UserController File





Below File is app\Http\Middleware\TestUser File
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TestUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        echo "<h3 class='text-primary'>Test User Middleware</h3>";
        return $next($request);
    }
}





Below File is app\Http\Middleware\ValidUser File
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class ValidUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $role): Response
    {
        echo "<h3 class='text-primary'>We are now in ValidUser Middleware.</h3>";
        echo "<h3 class='text-primary'>$role</h3>";

        if (Auth::check() && Auth::user()->role == $role) {
            return $next($request);
        } else if (Auth::user()->role == "reader") {
            return redirect()->route("user");
        } else {
            return redirect()->route("login");
        }
    }

    public function terminate(Request $request, Response $response): void
    {
        // When user's request completed then after "terminate()" method will call
        echo "<h3 class='text-danger'>We are now Terminating ValidUser Middleware.</h3>";
    }
}





Below File is app\Models\Post File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public $timestamps = true;
    protected $table = "posts";
    protected $fillable = ["title", "description", "user_id"];
}





Below File is app\Models\User File
<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;
    public $timestamps = true;
    protected $table = "users";

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<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',
        ];
    }
}





Below File is app\Providers\AppServiceProvider File
<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Gate::define("isAdmin", function (User $user) {
            return $user->role === "admin";
        });

        Gate::define("view-profile", function (User $user, $profileUser) {
            return $user->id === $profileUser;
        });

        // Below "$targetUser" value will get from URL
        Gate::define("update-post", function (User $user, $targetUser) {
            return $user->id === $targetUser;
        });

        Gate::define("delete-post", function (User $user, $targetUser) {
            return $user->id === $targetUser;
        });

        // before() method will execute before any of Gate methods, generally we use before() method to check
        // user is already loggedin or not
        Gate::before(function (User $user) {
            echo "Before Gate";
        });

        // after() method will execute after all Gate methods execution
        Gate::after(function (User $user) {
            echo "After Gate";
        });
    }
}





Below File is bootstrap\app File
<?php

use App\Http\Middleware\TestUser;
use App\Http\Middleware\ValidUser;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            "IsUserValid" => ValidUser::class
        ]);

        // Middleware groups
        // we can use "prependToGroup()" instead of "appendToGroup()" method
        // $middleware->appendToGroup("ok-user",[
        //     ValidUser::class,
        //     TestUser::class
        // ]);

        // Global Middleware
        // $middleware->append(TestUser::class);

        // If we want to apply multiple Global Middleware simultaneously then we can do as shown below :
        // $middleware->use([
        //     TestUser::class,
        //     ValidUser::class
        // ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();




Below File is database\json\posts File
[
    {
        "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        "description": "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",
        "user_id": 1
    },
    {
        "title": "Ut enim ad minim veniam, quis nostrud exercitation",
        "description": "ullamco laboris nisi ut aliquip ex ea commodo consequat",
        "user_id": 2
    },
    {
        "title": "Duis aute irure dolor in reprehenderit in voluptate velit",
        "description": "esse cillum dolore eu fugiat nulla pariatur",
        "user_id": 1
    },
    {
        "title": "Excepteur sint occaecat cupidatat non proident",
        "description": "sunt in culpa qui officia deserunt mollit anim id est laborum",
        "user_id": 3
    },
    {
        "title": "Sed ut perspiciatis unde omnis iste natus error sit",
        "description": "voluptatem accusantium doloremque laudantium",
        "user_id": 3
    },
    {
        "title": "totam rem aperiam, eaque",
        "description": "ipsa quae ab illo inventore veritatis et quasi architecto",
        "user_id": 2
    },
    {
        "title": "beatae vitae dicta sunt explicabo",
        "description": "Nemo enim ipsam voluptatem quia",
        "user_id": 1
    },
    {
        "title": "voluptas sit aspernatur aut odit aut fugit",
        "description": "sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt",
        "user_id": 2
    },
    {
        "title": "Neque porro quisquam est",
        "description": "qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
        "user_id": 3
    },
    {
        "title": "sed quia non numquam eius modi",
        "description": "tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem",
        "user_id": 2
    }
]





Below File is database\migrations\2024_12_26_051021_create_users_table File
<?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('users', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email");
            $table->string("password");
            $table->integer("age");
            $table->string("role");
            $table->timestamps();
        });
    }

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





Below File is database\migrations\2024_12_26_054403_create_posts_table File
<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->longText("description");
            $table->unsignedBigInteger("user_id");
            $table->foreign("user_id")->references("id")->on("users")->onUpdate("cascade")->onDelete("cascade");
            $table->timestamps();
        });
    }

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





Below File is database\seeders\DatabaseSeeder File
<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        $this->call([
            PostSeeder::class
        ]);
    }
}




Below File is database\seeders\PostSeeder File
<?php

namespace Database\Seeders;

use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database/json/posts.json");
        $posts = collect(json_decode($json));

        $posts->each(function ($post) {
            Post::create([
                "title" => $post->title,
                "description" => $post->description,
                "user_id" => $post->user_id
            ]);
        });
    }
}





Below File is resources\views\dashboard.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h1>Welcome, {{ Auth::user()->name }}</h1>
                    </div>
                    <div class="card-body">
                        {{ Auth::user() }}
                        <a href="{{ route("inner") }}" class="btn btn-primary mt-5">Go to Inner Page</a>

                        {{-- Below is the First way usage of "Gate" in blade file --}}
                        @if(Gate::allows("isAdmin"))
                            <a href="#" class="btn btn-success mt-5">Admin Panel</a>
                        @endif

                        {{-- Below is the Second way usage of "Gate" in blade file --}}
                        {{-- @can("isAdmin")
                            <a href="#" class="btn btn-success mt-5">Admin Panel</a>
                        @else
                            <a href="#" class="btn btn-success mt-5">Other Link</a>
                        @endcan --}}

                        {{-- Below is the opposite of above condition for "Gate" usage in blade file --}}
                        {{-- @cannot("isAdmin")
                            <a href="#" class="btn btn-success mt-5">Admin Panel</a>
                        @endcannot --}}


                        <a href="{{ route("profile.show",Auth::id()) }}" class="btn btn-primary mt-5">Profile</a>
                        <a href="{{ route("posts.show",Auth::id()) }}" class="btn btn-warning mt-5">Post</a>
                        <a href="{{ route("login") }}" class="btn btn-danger mt-5">Logout</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>




Below File is resources\views\inner.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Inner Page</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h1>Inner Page</h1>
                    </div>
                    <div class="card-body">
                        <a href="{{ route("dashboard") }}" class="btn btn-primary">Back to Dashboard</a>
                        <a href="{{ route("login") }}" class="btn btn-danger">Logout</a><br><br>
                        @if(auth()->check())
                            Id : {{ auth()->id() }},
                            Name : {{ Auth::user()->name }},
                            Email : {{ Auth::user()->email }},
                            Age : {{ Auth::user()->age }},
                            Role : {{ Auth::user()->role }}
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>




Below File is resources\views\login.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h3>Login</h3>
                    </div>
                    <div class="card-body">
                        <form action="{{ route("loginMatch") }}" method="POST">
                            @csrf
                            <div class="mb-3">
                                <label for="useremail" class="form-label">Email Address</label>
                                <input type="email" value="{{ old("email") }}" name="email" class="form-control @error("email") is-invalid @enderror" id="useremail" placeholder="Enter email"/>
                                <span class="text-danger">
                                    @error("email")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="userpassword" class="form-label">Password</label>
                                <input type="password" value="{{ old("password") }}" name="password" class="form-control @error("password") is-invalid @enderror" id="userpassword" placeholder="Enter password"/>
                                <span class="text-danger">
                                    @error("password")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <button type="submit" class="btn btn-primary">Login</button>
                            <a href="{{ route("welcomeTwo") }}" class="btn btn-secondary">Back</a>
                        </form>
                    </div>

                    @if($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</body>
</html>




Below File is resources\views\posts.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Post</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h1>Posts</h1>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-striped table-hover">
                            <thead>
                                <th>Id</th>
                                <th>Title</th>
                                <th>Description</th>
                                <th>Update</th>
                                <th>Delete</th>
                            </thead>

                            @foreach($posts as $data)
                                <tbody>
                                    <td>{{ $data->id }}</td>
                                    <td>{{ $data->title }}</td>
                                    <td>{{ $data->description }}</td>
                                    <td><a href="{{ route("post.update",$data->id) }}" class="btn btn-success">Update</a></td>
                                    <td><a href="" class="btn btn-danger">Delete</a></td>
                                </tbody>
                            @endforeach
                        </table>
                        <a href="{{ route("dashboard") }}" class="btn btn-secondary">Back</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>





Below File is resources\views\profile.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h1>Profile</h1>
                    </div>
                    <div class="card-body">
                        <table class="table">
                            <tr>
                                <th>Id</th>
                                <td>{{ $user->id }}</td>
                            </tr>
                            <tr>
                                <th>Name</th>
                                <td>{{ $user->name }}</td>
                            </tr>
                            <tr>
                                <th>Email</th>
                                <td>{{ $user->email }}</td>
                            </tr>
                            <tr>
                                <th>Age</th>
                                <td>{{ $user->age }}</td>
                            </tr>
                            <tr>
                                <th>Role</th>
                                <td>{{ $user->role }}</td>
                            </tr>
                        </table>
                        <a href="{{ route("dashboard") }}" class="btn btn-secondary">Back</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>





Below File is resources\views\register.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Register</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h3>Register</h3>
                    </div>
                    <div class="card-body">
                        <form action="{{ route("registerSave") }}" method="POST">
                            @csrf
                            <div class="mb-3">
                                <label for="username" class="form-label">Name</label>
                                <input type="text" value="{{ old("name") }}" name="name" class="form-control @error("name") is-invalid @enderror" id="username" placeholder="Enter username"/>
                                <span class="text-danger">
                                    @error("name")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="useremail" class="form-label">Email address</label>
                                <input type="email" value="{{ old("email") }}" name="email" class="form-control @error("email") is-invalid @enderror" id="useremail" placeholder="Enter email"/>
                                <span class="text-danger">
                                    @error("email")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="userage" class="form-label">Age</label>
                                <input type="text" value="{{ old("age") }}" name="age" class="form-control @error("age") is-invalid @enderror" id="userage" placeholder="Enter age"/>
                                <span class="text-danger">
                                    @error("age")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="userpassword" class="form-label">Password</label>
                                <input type="password" value="{{ old("password") }}" name="password" class="form-control @error("password") is-invalid @enderror" id="userpassword" placeholder="Enter password"/>
                                <span class="text-danger">
                                    @error("password")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="userpassword-confirm" class="form-label">Confirm Password</label>
                                <input type="password" value="{{ old("password_confirmation") }}" name="password_confirmation" class="form-control @error("password-confirmation") is-invalid @enderror" id="userpassword-confirm" placeholder="Enter confirm password"/>
                                <span class="text-danger">
                                    @error("password_confirmation")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <div class="mb-3">
                                <label for="userrole" class="form-label">Role</label>
                                <input type="text" value="{{ old("role") }}" name="role" class="form-control @error("role") is-invalid @enderror" id="userrole" placeholder="Enter role"/>
                                <span class="text-danger">
                                    @error("role")
                                        {{ $message }}
                                    @enderror
                                </span>
                            </div>
                            <button type="submit" class="btn btn-primary">Register</button>
                            <a href="{{ route("welcomeTwo") }}" class="btn btn-secondary">Back</a>
                        </form>
                    </div>

                    @if($errors->any())
                    <div class="card-footer text-body-secondary">
                        <div class="alert alert-danger">
                            <ul>
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</body>
</html>




Below File is resources\views\user.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Readers Page</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h3>Readers Page</h3>
                    </div>
                    <div class="card-body">
                        Hello, Reader
                        <a href="{{ route("logout") }}" class="btn btn-danger">Logout</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>





Below File is resources\views\welcomeTwo.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>welcomeTwo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-5 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h1 class="mb-5">Laravel Authentication</h1>
                    </div>
                    <div class="card-body">
                        <a href="{{ route("register") }}" class="btn btn-primary">Register</a>
                        <a href="{{ route("login") }}" class="btn btn-primary">Login</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>



Below File is routes\web.php File
<?php

use App\Http\Controllers\UserController;
use App\Http\Middleware\TestUser;
use App\Http\Middleware\ValidUser;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get("/user", function () {
    return view("user");
})->name("user");

Route::view("welcomeTwo", "welcomeTwo")->name("welcomeTwo");

Route::view("/register", "register")->name("register");

Route::view("/login", "login")->name("login");

Route::controller(UserController::class)->group(function () {
    Route::post("registerSave", "register")->name("registerSave");
    Route::post("/loginMatch", "login")->name("loginMatch");
    Route::post("/logout", "logout")->name("logout");
    Route::get("/dashboard", "dashboardPage")->name("dashboard");

    // we can pass "Gate" with route as shown below :
    // Route::get("/dashboard", "dashboardPage")->name("dashboard")->middleware("can:isAdmin");

    Route::get("dashboard/inner", "innerPage")->name("inner");
    Route::get("/profile/{id}", "ViewProfile")->name("profile.show");
    Route::get("/posts/{id}", "ViewPost")->name("posts.show");
    Route::get("/single-post/{id}", "UpdatePost")->name("post.update");
});

















Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11