php - 将 IP 白名单添加到 Laravel 5 维护模式时出错

标签 php laravel

我正在 Laravel 中配置维护模式。我正在尝试添加 IP 白名单。

当我运行这段代码时:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckForMaintenanceMode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
     public function handle($request, Closure $next)
     {
         if ($this->app->isDownForMaintenance() &&
             !in_array($request->getClientIP(), ['127.0.0.1']))
         {
             return response('Be right back!', 503);
         }

         return $next($request);
     }
}

我收到这个错误:

Undefined property: App\Http\Middleware\CheckForMaintenanceMode::$app

谁能告诉我问题出在哪里?

最佳答案

更新

从 Laravel 5.6.21 开始,此功能现已内置到 Laravel 中。 php artisan down 命令现在采用 --allow 参数,让您指定允许访问该站点的 IP 地址。

因此,无需进行任何自定义,您只需运行 php artisan down --allow=127.0.0.1

原创

您正在使用 $this->app,但您的类没有 $app 属性。你可以只使用 app() 辅助方法,你可以将 Application 注入(inject)你的中间件,或者你可以扩展 Laravel 的 CheckForMaintenanceMode 类,它将为您处理所有这些。

扩展 Laravel:

class CheckForMaintenanceMode extends \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode

依赖注入(inject):

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Foundation\Application;

class CheckForMaintenanceMode
{
    /**
     * The application implementation.
     *
     * @var \Illuminate\Contracts\Foundation\Application
     */
    protected $app;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
     public function handle($request, Closure $next)
     {
         if ($this->app->isDownForMaintenance() &&
             !in_array($request->getClientIP(), ['127.0.0.1']))
         {
             return response('Be right back!', 503);
         }

         return $next($request);
     }
}

app() 助手

 public function handle($request, Closure $next)
 {
     if (app()->isDownForMaintenance() &&
         !in_array($request->getClientIP(), ['127.0.0.1']))
     {
         return response('Be right back!', 503);
     }

     return $next($request);
 }

关于php - 将 IP 白名单添加到 Laravel 5 维护模式时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820302/

相关文章:

php - 如何在laravel中将css嵌入到HTML中?

java - 无法从 JSONObject 检索值

php - Internet Explorer 文件上传未通过 MIME 类型检查

PHP 无法从数据库下载上传的文件,因为使用中文文件名上传

laravel - 如何获得模型的空构建器?

php - "Unknown database type json requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it."运行 php artisan migrate 命令时

php - 根据 id mysql laravel 5 创建 uniqueID

javascript - 使用 AJAX 添加 select onchange

php - 为什么我没有收到 FCGI_END_REQUEST 记录?

laravel - 仅显示自己的帖子和 laravel 中管理员的所有帖子