Middleware used for filtering HTTP requests of your application.
Example
Laravel middleware that verifies the user of your application is authenticated or not.
If the user is not authenticated, the middleware will redirect the user to the login screen.
Laravel middleware such as authentication and CSRF protection, and all these are located in the app/Http/Middleware directory.
Create Middleware
To create a new middleware, use the make:middleware Artisan command.
php artisan make:middleware "name of the middleware"
php artisan make:middleware Checkuser
Example
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Checkuser{
public function handle($request, Closure $next) {
if(Auth::check() && Auth::user()->user_type == 1){
return $next($request);
}
else{
return redirect('/sign-in');
}
}
}
Route::get('/welcome', function () {
return view('welcome');
});
Route::group(['middleware' => 'checkuser', 'roles' => ['User']], function () {
Route::get('/dashboard', 'UserController@dashboard');
});
Copyright ©2022 coderraj.com. All Rights Reserved.