What is Middleware?.
Ans. Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel.
Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects to the login page.

2.How to Create Middleware?.
PHP artisan make:middleware “middleware_name” 

3.Register the middleware in kernel.php
'test' =>App\Http\Middleware\TestMiddleware::class,

4.How does Middleware work in Laravel?
In Laravel, middleware is defined in the application’s HTTP kernel, which is responsible for handling incoming HTTP requests. When a request is made to the application, the HTTP kernel passes the request through a series of middleware components before sending it to the appropriate controller. Each middleware component has the opportunity to process the request and modify it as necessary before passing it along to the next component.For example, a middleware component can be used to check if the user is authenticated before allowing access to certain routes. If the user is not authenticated, the middleware component can redirect the user to the login page. Another middleware component can be used to set a default language for the application based on the user’s browser language.

Here is an example of how you can use middleware in Laravel to
check if the user is authenticated:

class TestMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):
(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)
$next
* @return
\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
//check if user is not login redirect to login page
if (!auth()->check()) {
return redirect('login');
}
return $next($request);
}
}



Contact Us logo Whatsapp