在laravel中设置默认中间件
我是拉威尔框架的新手。我想设置一个中间件,它将在所有HTTP请求中调用。如何设置中间件?使用全局中间件。发件人:在laravel中设置默认中间件,laravel,laravel-5.5,Laravel,Laravel 5.5,我是拉威尔框架的新手。我想设置一个中间件,它将在所有HTTP请求中调用。如何设置中间件?使用全局中间件。发件人: 如果希望在应用程序的每个HTTP请求期间运行中间件,请在app/HTTP/Kernel.php类的$middleware属性中列出中间件类 如果希望中间件在应用程序的每个HTTP请求期间运行,请在app/HTTP/Kernel.php类的$middleware属性中列出中间件类,该类称为全局中间件 让我们举个例子 创建中间件 我们可以使用artisan轻松创建新的中间件 php ar
如果希望在应用程序的每个HTTP请求期间运行中间件,请在
app/HTTP/Kernel.php
类的$middleware
属性中列出中间件类
如果希望中间件在应用程序的每个HTTP请求期间运行,请在app/HTTP/Kernel.php类的$middleware属性中列出中间件类,该类称为全局中间件 让我们举个例子 创建中间件 我们可以使用artisan轻松创建新的中间件
php artisan make:middleware AdMiddleware
在我们创建了一个新的中间件组件之后,我们需要考虑修改代码以满足我们的需要
正在更新我们的中间件文件:
运行make:middleware命令后,您应该可以在app/http/middleware中看到新的中间件文件。打开它,我们将创建一个中间件,它将获取请求的IP地址,然后确定该请求来自哪个国家
<?php
namespace App\Http\Middleware;
use Closure;
class AdMiddleware {
/** * Handle an incoming request.
* * * @param \Illuminate\Http\Request $request
* * @param \Closure $next * @return mixed */
public function handle($request, Closure $next) { // Test to see if the requesters have an ip address.
if ($request->ip() == null) {
throw new \Exception("IP ADDRESS NOT SET");
} $country = file_get_contents('http://api.hostip.info/get_html.php?ip=' . $request->ip());
echo $country;
if (strpos($country, "UNITED STATES")) {
throw new \Exception("NOT FOR YOUR EYES, NSA");
} else {
return redirect("index");
} return $next($request);
}
}
第二种选择是让中间件仅在注册的路由上运行,您可以这样注册它:
<?php
/** * The application's route middleware.
* * * @var array */
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'ad' => \App\Http\Middleware\AdMiddleware::class,
];
<?php
/** * The application's route middleware.
* * * @var array */
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'ad' => \App\Http\Middleware\AdMiddleware::class,
];
Route::get('/ip', ['middleware' => 'ad', function() { return "IP"; }]);