Virus Corona (Covid-19)

Dapatkan Informasi terbaru

Tutorial Multi Auth (Authentication) di Laravel 6 / 7

Jackma 29 Apr 2020 9,990

Dalam tutorial ini, saya ingin berbagi dengan Anda cara membuat laravel 7/6 multiple authentication menggunakan middleware. kita akan membuat multi auth di laravel 7/6 menggunakan middleware. saya akan menulis tutorial langkah demi langkah untuk membuat multiple authentication di laravel 7/6.

Saya menulis banyak tutorial tentang multiple authentication di laravel. dalam tutorial ini kita akan membuat multi auth cara yang sangat sederhana menggunakan middleware dengan tabel tunggal.

Namun, dalam contoh ini, kami akan membuat cara yang sangat sederhana dan Anda dapat dengan mudah menggunakan aplikasi laravel 6 Anda. jadi mari ikuti langkah ini.

Step 1: Install Laravel 7/6

pertama-tama kita perlu mendapatkan aplikasi versi Laravel 6 baru menggunakan perintah di bawah ini, Jadi buka terminal ATAU command prompt Anda dan jalankan perintah di bawah ini:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Database Configuration

Pada langkah kedua, kita akan membuat konfigurasi basis data seperti nama basis data, nama pengguna, kata sandi, dll untuk aplikasi kasar kita di laravel 6. Jadi mari kita buka file .env dan isi semua detail seperti di bawah ini:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

Step 3: Update Migration and Model

Pada langkah ini, kita perlu menambahkan baris baru "is_admin" di tabel dan model user. dan kita perlu menjalankan migrasi. jadi mari kita ubah itu di kedua file.

database/migrations/000_create_users_table.php

<?php
   
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
   
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

app/User.php

<?php
   
namespace App;
   
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
   
class User extends Authenticatable
{
    use Notifiable;
   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'is_admin'
    ];
   
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
   
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Sekarang kita perlu menjalankan migrasi.

jadi mari kita jalankan perintah di bawah ini:

php artisan migrate

Step 4: Create Auth using scaffold

Sekarang, pada langkah ini, kita akan membuat perintah scaffold auth untuk membuat login, register dan dashboard. jadi jalankan perintah berikut:

Laravel 6 UI Package

composer require laravel/ui 

Generate auth

php artisan ui bootstrap --auth 
npm install
npm run dev

Step 5: Create IsAdmin Middleware

Pada langkah ini, kami harus membuat admin middleware yang hanya mengizinkan user akses admin ke route itu. jadi mari kita buat user admin dengan langkah-langkah berikut.

php artisan make:middleware IsAdmin

app/Http/middleware/IsAdmin.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
   
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
   
        return redirect(‘home’)->with(‘error’,"You don't have admin access.");
    }
}

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,
    'is_admin' => \App\Http\Middleware\IsAdmin::class,
];
....

Step 6: Create Route

Di sini, kita perlu menambahkan satu route lagi untuk beranda user admin jadi mari kita tambahkan route itu di file web.php.

routes/web.php

Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');

Step 7: Add Method on Controller

Di sini, kita perlu menambahkan metode adminHome() untuk orute admin di HomeController. jadi mari kita tambahkan seperti di bawah ini:

app/Http/Controllers/HomeController.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
   
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
    
}

Step 8: Create Blade file

Pada langkah ini, kita perlu membuat file blade create untuk admin dan update file blade user. jadi mari kita ubah.

resources/views/home.blade.php

@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">
                    You are normal user.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/adminHome.blade.php

@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">
                    You are Admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 9: Update on LoginController

Pada langkah ini, kita akan rubah pada LoginController, ketika pengguna akan login yang kita redirect sesuai dengan akses pengguna. jika user normal maka kami akan mengalihkan ke route home dan jika user admin kami mengarahkan ke route admin. jadi mari kita rubah.

app/Http/Controllers/Auth/LoginController.php

<?php
  
namespace App\Http\Controllers\Auth;
   
use App\Http\Controllers\Controller;
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 = '/home';
   
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
   
    public function login(Request $request)
    {   
        $input = $request->all();
   
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
   
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->is_admin == 1) {
                return redirect()->route('admin.home');
            }else{
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }
          
    }

Step 10: Create Seeder

Kami akan membuat seeder untuk membuat admin baru dan user normal. jadi mari kita buat seeder menggunakan perintah berikut:

php artisan make:seeder CreateUsersSeeder

database/seeds/CreateUsersSeeder.php

<?php
  
use Illuminate\Database\Seeder;
use App\User;
   
class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = [
            [
               'name'=>'Admin',
             'email'=>'admin@medikre.com',
                'is_admin'=>'1',
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'User',
             'email'=>'user@medikre.com',
                'is_admin'=>'0',
               'password'=> bcrypt('123456'),
            ],
        ];
  
        foreach ($user as $key => $value) {
            User::create($value);
        }
    }
}

Sekarang mari kita jalankan seeder:

php artisan db:seed --class=CreateUsersSeeder

Ok, sekarang kita siap untuk running.

Jadi mari kita jalankan project menggunakan perintah ini:

php artisan serve

Admin User

Email: admin@medikre.com
Password: 123456

User Normal

Email: user@medikre.com
Password: 123456

Saya harap ini dapat membantu Anda ...

Tags

multi auth laravel laravel 6 laravel 7 laravel

Related Stories


Latest Stories


Close Ads X