Cara Membuat Beberapa Otentikasi Pada Aplikasi Laravel 9 - CRUDPRO

Cara Membuat Beberapa Otentikasi Pada Aplikasi Laravel 9

Cara Membuat Beberapa Otentikasi Pada Aplikasi Laravel 9

Pertama, Anda perlu mengunduh aplikasi laravel baru menggunakan perintah berikut:

composer create-project laravel/laravel laravel-multi-auth

Kemudian pindah ke direktori project.

cd laravel-multi-auth

1. Pengaturan Database Connection

Buat koneksi database dan buka file .env untuk menentukan detail database. Ini memberikan konsensus antara laravel dan database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

2. Setting Migration dan Setup database

Kemudian gunakan file migrasi untuk menambahkan kolom is_admin ke tabel users. Oleh karena itu, buka file migrasi create_users_table.php yang terletak di Database/Migration dan perbarui field berikut di admin:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->tinyInteger('type')->default(0);
            /* Users: 0=>User, 1=>Admin, 2=>Manager */
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

Kemudian buka app/User.php dan update nama field berikut is_admin disini.

<?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;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Authenticatable {
    use HasApiTokens, HasFactory, Notifiable;
    protected $fillable = ['name', 'email', 'password', 'type'];
    protected $hidden = ['password', 'remember_token', ];
    protected $casts = ['email_verified_at' => 'datetime', ];
    protected
    function type(): Attribute {
        return new Attribute(get: fn($value) => ["user", "admin", "manager"][$value], );
    }
}

Sekarang tambahkan file is_admin. Kemudian buat field ini di database menggunakan perintah berikut:

php artisan migrate

Sekarang, buat sistem otentikasi bawaan. Gunakan perintah di bawah ini untuk membuat sistem auth default di laravel. Dan ubah sistem auth bawaan laravel ke sistem multi auth

Perintah ini akan membuat route, controller, dan file tampilan untuk Otentikasi dan Registrasi Login Laravel. Ini berarti untuk memberikan otentikasi login laravel dasar dan sistem pendaftaran Lengkap. Mari kita buka command prompt dan ketik perintah di bawah ini.

otentikasi bawaan laravel menjadi sistem multi-auth

Perintah ini membuat file root, controller, dan view untuk otentikasi dan registrasi login Laravel. Ini berarti menyediakan sistem otentikasi dan registrasi login laravel yang lengkap. Buka prompt perintah dan coba ketikkan perintah berikut:

3. Selanjutnya, instal laravel9UI di project Anda menggunakan perintah berikut.

composer require laravel/ui

Kemudian jalankan perintah berikut di terminal untuk membuat login, registrasi, lupa kata sandi, dan mengatur ulang file blade kata sandi.

php artisan ui bootstrap --auth

Kemudian jalankan perintah berikut:

npm install
npm run dev

4. Buat middleware UserAccess

Pada langkah ini, Anda perlu membuat middleware akses users yang membatasi users mengakses halaman. Sekarang mari kita tulis dan perbarui kodenya.

php artisan make:middleware UserAccess

app/Http/middleware/UserAccess.php

<?php
namespaceApp\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class UserAccess
{ /*** Handle an incoming request.** @param  \Illuminate\Http\Request  $request* @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse*/
    public function handle(Request $request, Closure $next, $userType)
    {
        if (auth()->user()->type == $userType)
        {
            return $next($request);
        }
        return response()->json(['You do not have permission to access for this page.']); /* return response()->view('errors.check-permission'); */
    }
}

app/Http/Kernel.php

....
    protected $routeMiddleware = ['auth' => 
    \App\Http\Middleware\Authenticate::class,'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,'can' => \Illuminate\Auth\Middleware\Authorize::class,'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,'user-access' => \App\Http\Middleware\UserAccess::class,];....

5. Buat route

Di sini, Kami akan menambahkan grup rute berikut tempat Anda dapat membuat rute baru untuk akses pengguna, admin, dan pengelola. mari perbarui kode:

routes/web.php

<?php
useIlluminate\Support\Facades\Route;
use App\Http\Controllers\HomeController; /*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/
Route::get('/', function ()
{
    return view('welcome');
});
Auth::routes(); /*--------------------------------------------------------------------------------------All Normal Users Routes List----------------------------------------------------------------------------------------*/
Route::middleware(['auth', 'user-access:user'])->group(function ()
{
    Route::get('/home', [HomeController::class , 'index'])
        ->name('home');
}); /*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/
Route::middleware(['auth', 'user-access:admin'])->group(function ()
{
    Route::get('/admin/home', [HomeController::class , 'adminHome'])
        ->name('admin.home');
}); /*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/
Route::middleware(['auth', 'user-access:manager'])->group(function ()
{
    Route::get('/manager/home', [HomeController::class , 'managerHome'])
        ->name('manager.home');
});

6. Pembaruan controller

Di sini kita perlu menambahkan metode adminHome() dan managerHome ke root admin HomeController. Mari kita tambahkan:

app/Http/Controllers/HomeController.php

<?php
namespaceApp\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        return view('home');
    }
    public function adminHome()
    {
        return view('adminHome');
    }
    public function managerHome()
    {
        return view('managerHome');
    }
}

7. Konfigurasikan tampilan blade

Buka file resources/views/home.blade.php yang telah ditentukan dan masukkan kode dasar di dalam file.

@extends('layouts.app')@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>                
                    <div class="card-body">
                    @if(session('login-success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('login-success') }}
                        </div>
                    @endif
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif                    You are normal user.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Buat dan buka file resources/views/admin-home.blade.php dan tambahkan kodenya:

@extends('layouts.app')@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>                <div class="card-body">
                    @if(session('login-success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('login-success') }}
                        </div>
                    @endif
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif                    You are admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

8. Konfigurasikan controller Masuk

Pada langkah ini, Anda mengonfigurasi kelas LoginController, menentukan metode login(), dan memasukkan kode berikut. Menangani validasi sisi server dan mengalihkan ke dasbor admin jika users yang masuk adalah admin.

Sertakan kode berikut dalam file app/Http/Controllers/Auth/LoginController.php

<?php 
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */    use AuthenticatesUsers;    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }    public function login(Request $request)
    {
        $request->validate([
            'email'     => 'required|email',
            'password'  => 'required'
        ]);        $credentials = $request->only('email', 'password');        if(! auth()->attempt($credentials)){
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }        if (auth()->user()->is_admin == 1) {
            return redirect()->route('admin.home');
        }        return redirect()->route('home');
    }
}

9. Buat data dummy menggunakan Seeder

Oleh karena itu, gunakan perintah berikut untuk membuat seeder users.

php artisan make:seeder UsersSeeder
Kemudian buka file database/seed/UsersSeeder.php dan masukkan data berikut:
<?php 
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $usersData = [
            [
               'name'   =>'Admin',
               'email'  =>'[email protected]',
               'is_admin' => 1,
               'password' => Hash::make('12345678')
            ],
            [
               'name'       => 'User',
               'email'      => '[email protected]',
               'is_admin'   => 0,
               'password'   => Hash::make('12345678')
            ],
        ];        foreach ($usersData as $key => $val) {
            User::create($val);
        }
    }
}

10. Jalankan aplikasi dan tes Laravel MultiAuth

Aktifkan aplikasi multi-otentikasi laravel menggunakan perintah berikut:

php artisan serve

Buka URL berikut di browser Anda: http://127.0.0.1:8000/login

Dasbor manajemen:

Gunakan kredensial berikut untuk dasbor manajemen.

Email: [email protected]
Password: 12345678

Di sini tampilan ini ditampilkan setelah masuk menggunakan peran admin

Dasbor users:

Gunakan kredensial berikut untuk dasbor manajemen.

Email: [email protected]
Password: 12345678

Di sini tampilan ini ditampilkan setelah masuk menggunakan login users biasa

login users

Apakah Anda menyukai Tutorial Multi-Autentikasi Laravel langkah demi langkah? Jadi jangan lupa untuk membagikannya kepada orang lain. Semoga harimu menyenangkan.