middleware laravel auth code example
Example 1: laravel auth
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
Example 2: create new authentication middleware laravel
php artisan make:middleware BasicAuth //In console.
//BasicAuth.php file is created:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuth {
public function handle($request, Closure $next) {
return $next($request);
}
}
public function handle($request, Closure $next) {
$isAuthenticatedAdmin = (Auth::check() && Auth::user()->admin == 1);
if (! $isAuthenticatedAdmin)
return redirect('/login')->with('message', 'Authentication Error.');
return $next($request);
}
protected $routeMiddleware = [
'adminAuth' => \App\Http\Middleware\AdminAuth::class
];
Route::get('/adminsite', function () {
return view('adminsite');
})->middleware('adminAuth');
Example 3: laravel auth namespace
use Illuminate\Support\Facades\Auth;
Example 4: laravel set middleware default
If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.
Example 5: laravel force login by id
Auth::login($user);