laravel middleware auth route code example
Example 1: 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 2: laravel auth namespace
use Illuminate\Support\Facades\Auth;
Example 3: middleware command in laravel
php artisan make:middleware NameOfTheMiddleware
Example 4: 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 5: 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);
}
}
Example 6: laravel force login by id
Auth::login($user);