Cara buat fitur banned login di laravel
Mastama.my.id - Hari ini, saya ingin menunjukkan kepada Anda Cara Memblokir/Menangguhkan Pengguna di Laravel. Anda dapat melihat contoh akun pengguna larangan laravel. Tutorial ini akan memberi Anda contoh sederhana dari contoh fitur banned laravel. jika Anda ingin melihat contoh pengguna yang mengaktifkan nonaktifkan laravel maka Anda adalah tempat yang tepat. ikuti langkah bellow untuk Contoh fitur banned laravel.
Sebagian besar akan membutuhkan untuk membuat fitur banned laravel pengguna dan mencabut fungsionalitas untuk alasan keamanan. Jika Anda mengembangkan aplikasi web besar maka harus diperlukan untuk mengaktifkan dan menonaktifkan pengguna saat pengguna admin menginginkannya. Karena beberapa pengguna membuat aktivitas di situs web kami maka kami dapat melarang pengguna tersebut. Jadi pada dasarnya ada baiknya jika Anda memberikan fitur banned laravel pengguna dan mencabut fungsionalitas ke klien pada aplikasi laravel 5 Anda.
Pada artikel ini, kita akan mempelajari cara membuat fungsionalitas ban dan mencabut di aplikasi laravel 5 menggunakan paket komposer fitur banned laravel. Paket Laravel-ban memberi kita pilihan untuk mengirim pengguna ban untuk waktu tertentu dan ada beberapa hal. Ini menarik jadi kami akan membuat contoh lengkap fitur banned laravel pengguna dan mencabut dari awal.
Anda dapat menggunakan contoh ini dengan versi laravel 6, laravel 7, laravel 8 dan laravel 9.
Anda harus mengikuti langkah bellow dan Anda akan mendapatkan tata letak seperti bellow:
Langkah Pertama
Install Laravel
Ini opsional; namun, jika Anda belum membuat aplikasi laravel, maka Anda dapat melanjutkan dan menjalankan perintah di bawah ini:
composer create-project laravel/laravel example-app
Langkah Kedua
Konfigurasi Database
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)
Langkah Ketiga
Buat laravel auth
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev
Langkah KeEmpat
Install package dan Konfigurasi
composer require cybercog/laravel-ban
<?php
return [
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
....
Cog\Laravel\Ban\Providers\BanServiceProvider::class,
],
.....
php artisan vendor:publish --provider="Cog\Laravel\Ban\Providers\BanServiceProvider" --tag="migrations"
php artisan migrate
Langkah 5:
Tambahkan Migation dan Model Config.
php artisan make:migration add_banned_at_column_to_users_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddBannedAtColumnToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('banned_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('banned_at');
});
}
}
php artisan migrate
<?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 Cog\Contracts\Ban\Bannable as BannableContract;
use Cog\Laravel\Ban\Traits\Bannable;
class User extends Authenticatable implements BannableContract
{
use HasApiTokens, HasFactory, Notifiable, Bannable;
/**
* 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',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Langkah 6:
Buat Middleware
php artisan make:middleware ForbidBannedUserCustom
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
class ForbidBannedUserCustom
{
/**
* The Guard implementation.
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
* @param \Illuminate\Contracts\Auth\Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$user = $this->auth->user();
if ($user && $user->isBanned()) {
\Session::flush();
return redirect('login')->withInput()->withErrors([
'email' => 'This account is blocked.',
]);
}
return $next($request);
}
}
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
......
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
....
'is-ban' => \App\Http\Middleware\ForbidBannedUserCustom::class,
];
}
Langkah 7:
Tambahkan Route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Auth::routes();
Route::group(['middleware'=>'is-ban'], function(){
Route::get('/home',[HomeController::class,'index'])->name('home');
Route::get('users',[UserController::class,'index'])->name('users.index');
Route::post('userBan',[UserController::class,'ban'])->name('users.ban');
Route::get('userUserRevoke/{id}',[UserController::class,'revoke'])->name('users.revokeuser');
});
Langkah 8:
Tambahkan Controller
<?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\Http\Response
*/
public function index()
{
return view('home');
}
}
&ly;?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Models\User;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::get();
return view('users',compact('users'));
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function ban(Request $request)
{
$input = $request->all();
if(!empty($input['id'])){
$user = User::find($input['id']);
$user->bans()->create([
'expired_at' => '+1 month',
'comment'=>$request->baninfo
]);
}
return redirect()->route('users.index')->with('success','Ban Successfully..');
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function revoke($id)
{
if(!empty($id)){
$user = User::find($id);
$user->unban();
}
return redirect()->route('users.index')
->with('success','User Revoke Successfully.');
}
}
Langkah 9:
Buat View
@extends('layouts.app')
@section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="card">
<div class="card-header text-center">
<h1>Users Management</h1>
</div>
<div class="card-body">
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Is Ban?</th>
<th>Action</th>
</tr>
@if($users->count())
@foreach($users as $key => $user)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
@if($user->isBanned())
<label class="label label-danger">Yes</label>
@else
<label class="label label-success">No</label>
@endif
</td>
<td>
@if($user->isBanned())
<a href="{{ route('users.revokeuser',$user->id) }}" class="btn btn-success btn-sm"> Revoke</a>
@else
<a class="btn btn-success ban btn-sm" data-id="{{ $user->id }}" data-action="{{ URL::route('users.ban') }}"> Ban</a>
@endif
</td>
</tr>
@endforeach
@endif
</table>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("body").on("click",".ban",function(){
var current_object = $(this);
bootbox.dialog({
message: "<form class='form-inline add-to-ban' method='POST'><div class='form-group'><textarea class='form-control reason' rows='4' style='width:500px' placeholder='Add Reason for Ban this user.'></textarea></div></form>",
title: "Add To Black List",
buttons: {
success: {
label: "Submit",
className: "btn-success",
callback: function() {
var baninfo = $('.reason').val();
var token = $("input[name='_token']").val();
var action = current_object.attr('data-action');
var id = current_object.attr('data-id');
if(baninfo == ''){
$('.reason').css('border-color','red');
return false;
}else{
$('.add-to-ban').attr('action',action);
$('.add-to-ban').append('<input name="_token" type="hidden" value="'+ token +'">')
$('.add-to-ban').append('<input name="id" type="hidden" value="'+ id +'">')
$('.add-to-ban').append('<input name="baninfo" type="hidden" value="'+ baninfo +'">')
$('.add-to-ban').submit();
}
}
},
danger: {
label: "Cancel",
className: "btn-danger",
callback: function() {
// remove
}
},
}
});
});
</script>
@endsection
Langkah 10:
Buat Seeder
php artisan make:seeder UserTableSeeder
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$users = [
['name'=>'Admin', 'email'=>'admin@gmail.com','password'=>bcrypt('123456')],
['name'=>'User', 'email'=>'user@gmail.com','password'=>bcrypt('123456')],
['name'=>'Head', 'email'=>'head@gmail.com','password'=>bcrypt('123456')]
];
foreach ($users as $key => $value) {
User::create($value);
}
}
}
php artisan db:seed --class=UserTableSeeder