laravel中的中间件是什么? [英] What is middleware in laravel?

查看:192
本文介绍了laravel中的中间件是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解中间件如何在Laravel中工作.这是我的课程,任何人都可以解释它的工作原理.吗?

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);
    }

}

谢谢

推荐答案

Middleware提供了一种方便的机制,用于过滤进入您的应用程序的HTTP请求.例如,Laravel包括一个middleware,用于验证您的应用程序的用户已通过身份验证.如果用户未通过身份验证,则middleware会将用户重定向到登录屏幕.但是,如果用户通过了身份验证,则middleware将允许请求继续进行到应用程序中.

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.

参考

如@ num8er

中间件是介于路由器和路由处理程序之间的功能(或逻辑).

Middleware is the function (or logic) that stands between router and route handler.

在您的代码中:

public function handle($request, Closure $next)
{
    if ($request->age <= 200) {
        return redirect('home');
    }

    return $next($request);
}

$request->age是请求中提供的变量,可以在每个HTTP请求中进行检查,如果其值<= 200则用户将重定向到本地路由.

$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.

这篇关于laravel中的中间件是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆