middleware auth laravel code example

Example 1: laravel check auth

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

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 {
	/**
	* Handle an incoming request.
	*
	* @param  \Illuminate\Http\Request  $request
	* @param  \Closure  $next
	* @return mixed
	*/
	public function handle($request, Closure $next) {
		return $next($request);
	}
}

//Replace handle function:
public function handle($request, Closure $next) {
	//The following line(s) will be specific to your project, and depend on whatever you need as an authentication.
  	$isAuthenticatedAdmin = (Auth::check() && Auth::user()->admin == 1);
  
  	//This will be excecuted if the new authentication fails.
	if (! $isAuthenticatedAdmin)
		return redirect('/login')->with('message', 'Authentication Error.');
	return $next($request);
}

//In app/Http/Kernel.php, add this line:
protected $routeMiddleware = [
	/*
	* All the laravel-defined authentication methods
	*/
  'adminAuth' => \App\Http\Middleware\AdminAuth::class //Registering New Middleware
];

//In routes/web.php, add this at the end of the desired routes:
Route::get('/adminsite', function () {
	return view('adminsite');
})->middleware('adminAuth'); //This line makes the route use your new authentication middleware.

Example 3: middleware command in laravel

php artisan make:middleware NameOfTheMiddleware

Example 4: laravel auth

composer require laravel/ui:^2.4

php artisan ui vue --auth

Example 5: laravel middleware

// Within App\Http\Kernel Class...

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 6: middleware in laravel

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}