
آموزش ایجاد وضعیت کاربر آنلاین / آفلاین در لاراول
در این نوشته نحوه ایجاد وضعیت کاربر آنلاین / آفلاین آموزش می دهیم که چگونه خروجی وضعیت کاربر در لاراول را دریافت کنید. نحوه کار این است که کاربر هر بار ورود و خروج از صفحه وضعیت آنلاین / آفلاین در میزکار مدیر نمایش دهد.
۱. ستون دیتابیس را با نام add_new_column_last_seen ایجاد کنید:
php artisan make:migration add_new_column_last_seen
۲. یک جدول جدید با نام last_seen ایجاد کنید:
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddNewColumnLastSeen extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function(Blueprint $table){ $table->timestamp('last_seen')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { } }
۳. دستور زیر در خط فرمان لینوکس یا ویندوز وارد کنید تا اطلاعات جدول و ستون ثبت شود:
php artisan migrate
۴. در مسیر مدل app/Models/User.php عبارت last_seen را اضافه کنید:
<?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, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'last_seen' ]; /** * 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', ]; }
۵. یک فایل جدید به نام UserActivity در بخش middleware ایجاد کنید:
php artisan make:middleware UserActivity
۶. کد زیر را در فایل UserActivity.php وارد کنید:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Auth; use Cache; use App\Models\User; class UserActivity { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { if (Auth::check()) { $expiresAt = now()->addMinutes(2); /* keep online for 2 min */ Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt); /* last seen */ User::where('id', Auth::user()->id)->update(['last_seen' => now()]); } return $next($request); } }
۷. در قسمت هسته لاراول فایل UserActivity.php را در مسیر app/Http/Kernel.php فراخوانی کنید:
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { ........... protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\RestrictIpAddressMiddleware::class, \App\Http\Middleware\UserActivity::class, ], 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; ........... }
۸. مسیر صفحه در web.php تعریف کنید:
Route::middleware(['auth', 'admin'])->prefix('/userarea')->group(function() { Route::resource('/users', UserController::class)->except(['show']); });
۹. کنترلر با نام UserController.php در مسیر app/Http/Controllers/UserController.php ایجاد کنید و کد زیر را قرار دهید:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $users = User::select("*") ->whereNotNull('last_seen') ->orderBy('last_seen', 'DESC') ->paginate(10); return view('users', compact('users')); } }
۱۰. برای نمایش وضعیت آنلاین / آفلاین کاربر فایل به نام users.blade.php در مسیر resources/views/users.blade.php ایجاد کنید و کد زیر را قرار دهید:
<x-panel-layout> <div class="d-grid gap-2 d-md-flex justify-content-md-start mb-3"> <a class="btn btn-primary me-md-2" href="{{route('users.index')}}"><i class="fas fa-users"></i> همه کاربران</a> <a class="btn btn-primary" href="{{route('users.create')}}"><i class="fas fa-user-plus"></i> ایجاد کاربر جدید</a> </div> <table class="table table-bordered"> <thead> <tr> <th scope="col">شناسه</th> <th scope="col">نام و نام خانوادگی</th> <th scope="col">ایمیل</th> <th scope="col">سطح کاربری</th> <th scope="col">تاریخ عضویت</th> <th scope="col">وضعیت کاربر</th> <th scope="col">عملیات</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <th scope="row">{{ $user->id }}</th> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->role }}</td> <td>{{ $user->getCreatedAtInJalali() }}</td> <td class="text-center"> @if(Cache::has('user-is-online-' . $user->id)) <span class="text-success"><i class="fas fa-circle"></i> آنلاین</span> @else <span class="text-secondary"><i class="fas fa-circle"></i> آفلاین</span> @endif </td> <td class="text-center"> @if (auth()->user()->id !== $user->id && $user->role !== 'admin') <a href="{{ route('users.destroy', $user->id) }}" onclick="destroyUser(event, {{ $user->id }})"><i class="fas fa-trash"></i></a> @endif <a href="{{route('users.edit', $user->id)}}"><i class="fas fa-edit"></i></a> <form action="{{ route('users.destroy', $user->id) }}" method="post" id="destroy-user-{{ $user->id }}"> @csrf @method('DELETE') </form> </td> </tr> @endforeach </tbody> </table> {{ $users->links() }} </x-panel-layout>
۱۱ . پیش نمایش :
موفق باشید 🙂