I'm trying to understand how the middleware works in Laravel. Here's my class can any one explain how does its works.?
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
}
Thanks
Middleware
provide a convenient mechanism for filtering HTTP
requests entering your application. For example, Laravel
includes a middleware
that verifies the user of your application is authenticated. If the user is not authenticated, the middleware
will redirect the user to the login screen. However, if the user is authenticated, the middleware
will allow the request to proceed further into the application.
Reference
Edit: As explained by @num8er
Middleware is the function (or logic) that stands between router and route handler.
In your code:
public function handle($request, Closure $next)
{
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
$request->age
is a variable that provided in request and can be checked on each HTTP request, if its value <= 200
then user redirects to home route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With