Laravel 8 Online Offline Users Example
Hello,
In the present day, i we are going to present you laravel Eight on-line offline customers instance. This text will provide you with easy instance of laravel Eight on-line offline customers instance. you’ll be taught laravel Eight on-line offline customers instance. So let’s comply with few step to create instance of laravel Eight on-line offline customers instance.
Step 1: Set up Laravel
we have to set up Laravel 8. So open your terminal OR command immediate and run bellow command:
composer create-project --prefer-dist laravel/laravel weblog
Step 2: Add New Column to Customers Desk
create new migration for including “last_seen” column:
php artisan make:migration add_new_column_last_seen
database/migrations/2021_07_12_032305_add_new_column_last_seen.php
<?php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class AddNewColumnLastSeen extends Migration { /** * Run the migrations. * * @return void */ public operate up() { Schema::desk('customers', operate(Blueprint $desk){ $table->timestamp('last_seen')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public operate down() { } }
run migration command:
php artisan migrate
simply add last_seen column on person mannequin
app/Fashions/Consumer.php
<?php namespace AppModels; use IlluminateContractsAuthMustVerifyEmail; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateFoundationAuthUser as Authenticatable; use IlluminateNotificationsNotifiable; class Consumer extends Authenticatable { use HasFactory, Notifiable; /** * The attributes which might be mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'last_seen', ]; /** * The attributes that ought to be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that ought to be solid to native sorts. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }
Step 3: Generate Auth Scaffolding
laravel ui for producing auth scaffolding, so let’s run bellow command:
composer require laravel/ui --dev
putting in composer package deal, run bellow command:
php artisan ui bootstrap --auth
run npm set up instructions:
npm set up npm run dev
Step 4: Create Middleware
create UserActivity for replace final seen time and add on-line standing, let’s run bellow command:
php artisan make:middleware UserActivity
replace middleware code
app/Http/Middleware/UserActivity.php
<?php namespace AppHttpMiddleware; use Closure; use IlluminateHttpRequest; use Auth; use Cache; use AppModelsUser; class UserActivity { /** * Deal with an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $subsequent * @return combined */ public operate deal with(Request $request, Closure $subsequent) { if (Auth::test()) { $expiresAt = now()->addMinutes(2); /* hold on-line for two min */ Cache::put('user-is-online-' . Auth::person()->id, true, $expiresAt); /* final seen */ Consumer::the place('id', Auth::person()->id)->replace(['last_seen' => now()]); } return $subsequent($request); } }
now register, this middleware to kernel file:
app/Http/Kernel.php
<?php namespace AppHttp; use IlluminateFoundationHttpKernel as HttpKernel; class Kernel extends HttpKernel { /** * The appliance's world HTTP middleware stack. * * These middleware are run throughout each request to your utility. * * @var array */ protected $middleware = [ // AppHttpMiddlewareTrustHosts::class, AppHttpMiddlewareTrustProxies::class, FruitcakeCorsHandleCors::class, AppHttpMiddlewarePreventRequestsDuringMaintenance::class, IlluminateFoundationHttpMiddlewareValidatePostSize::class, AppHttpMiddlewareTrimStrings::class, IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class, ]; /** * The appliance's route middleware teams. * * @var array */ protected $middlewareGroups = [ 'web' => [ AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, // IlluminateSessionMiddlewareAuthenticateSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, IlluminateRoutingMiddlewareSubstituteBindings::class, AppHttpMiddlewareUserActivity::class, ], 'api' => [ 'throttle:api', IlluminateRoutingMiddlewareSubstituteBindings::class, ], ]; /** * The appliance's route middleware. * * These middleware could also be assigned to teams or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => AppHttpMiddlewareAuthenticate::class, 'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, 'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class, 'can' => IlluminateAuthMiddlewareAuthorize::class, 'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class, 'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class, 'signed' => IlluminateRoutingMiddlewareValidateSignature::class, 'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class, 'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class, ]; }
Step 5: Create Route
create some routes for show on-line customers operate.
routes/net.php
<?php use IlluminateSupportFacadesRoute; use AppHttpControllersUserController; /* |-------------------------------------------------------------------------- | Internet Routes |-------------------------------------------------------------------------- | | Right here is the place you may register net routes to your utility. These | routes are loaded by the RouteServiceProvider inside a gaggle which | comprises the "net" middleware group. Now create one thing nice! | */ Route::get('/', operate () { return view('welcome'); }); Auth::routes(); Route::get('/house', [AppHttpControllersHomeController::class, 'index'])->identify('house'); Route::get('online-user', [UserController::class, 'index']);
Step 6: Create Controller
this step, we have to create UserController and add following code:
app/Http/Controllers/UserController.php
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; class UserController extends Controller { /** * Show an inventory of the useful resource. * * @return IlluminateHttpResponse */ public operate index(Request $request) { $customers = Consumer::choose("*") ->whereNotNull('last_seen') ->orderBy('last_seen', 'DESC') ->paginate(10); return view('customers', compact('customers')); } }
Step 7: Create Blade Information
create blade information for customers. so let’s create:
assets/views/customers.blade.php
@extends('layouts.app') @part('content material') <div class="container"> <h1>Laravel Eight On-line Offline Customers Instance - codeplaners.com</h1> <hyperlink rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <desk class="desk table-bordered data-table"> <thead> <tr> <th>No</th> <th>Title</th> <th>Electronic mail</th> <th>Final Seen</th> <th>Standing</th> </tr> </thead> <tbody> @foreach($customers as $person) <tr> <td>{{ $user->id }}</td> <td>{{ $user->identify }}</td> <td>{{ $user->electronic mail }}</td> <td> {{ CarbonCarbon::parse($user->last_seen)->diffForHumans() }} </td> <td> @if(Cache::has('user-is-online-' . $user->id)) <span class="text-success">On-line</span> @else <span class="text-secondary">Offline</span> @endif </td> </tr> @endforeach </tbody> </desk> </div> @endsection
able to run our instance:
php artisan serve
Hope this instance may help you…
Komentar
Posting Komentar