laravel add auth middleware to route code example
Example 1: create new authentication middleware laravel
php artisan make:middleware BasicAuth
<?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 2: laravel middleware
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
Example 3: laravel middleware
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
}