Cara Mudah Cek Session Dengan Middleware Pada Laravel

Penggunaan session pasti sudah umum untuk membuat login dan pengecekan login (authentication).

Disini kita membagi middleware menjadi 2 :

Diantara kedua tsb User dan Guest adalah pengecekan yang berbeda berdasarkan login.

1. Membuat Middleware CheckUserSession

php artisan make:middleware CheckUserSession

Kemudian pada app\Http\Middleware\CheckUserSession.php ubah seperti ini.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckUserSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->session()->exists('user')) return redirect('/');
        
        return $next($request);
    }
}

2. Membuat Middleware CheckGuestSession

php artisan make:middleware CheckGuestSession

Kemudian pada app\Http\Middleware\CheckGuestSession.php ubah seperti ini.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckGuestSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->session()->exists('user')) return redirect()->route('dashboard.index');
        
        return $next($request);
    }
}

3. Menambahkan routeMiddleware Pada app\Http\Kernel.php

'user.session' => \App\Http\Middleware\CheckUserSession::class,
'guest.session' => \App\Http\Middleware\CheckGuestSession::class,

4. Menambahkan Middleware Pada Route routes\web.php

Route::group(['middleware' => 'guest.session'], function () {
    Route::get('login', 'AuthController@login')->name('login.index');
    Route::post('login', 'AuthController@login')->name('login.post');
});
Route::group(['middleware' => 'user.session'], function () {
    Route::get('dashboard', 'DashboardController@index')->name('dashboard.index');
    Route::get('logout', 'AuthController@logout')->name('logout');
});

5. Menambahkan Session Pada Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        if ($request->isMethod('post')) {
            $this->validate(
                $request,
                [
                    'username' => 'required',
                    'password' => 'required|min:5|max:20',
                ]
            );
            
            $request->session()->put('user.username', $request->username);
        }
        
        return view('auth/login');
    }
    
   public function logout(Request $request)
    {
        $request->session()->flush();
        
        return redirect()->route('login.index');
    }
}

Sekian untuk kali ini semoga bermanfaat :D untuk lebih lanjut bisa kunjungi link tersebut.