【问题标题】:Laravel 8 Gate base on Levels in Database Artisan Migration errorLaravel 8 Gate 基于数据库工匠迁移错误中的级别
【发布时间】:2021-08-17 04:06:04
【问题描述】:

我是 Laravel 8 的新手,我正在根据数据库中的用户级别实现 Gates。 非常类似于角色。

我的桌子等级看起来像这样 id、name、gate、timestamp

这是我在 /app/Providers/AuthServiceProvider 中的代码

...
...
    public function boot()
    {
        $this->registerPolicies();
        
        /*
         * Gate base on Level in the Database
         */
        $levels = Level::all();
        foreach ($levels as $level) {
            $gate = $level->gate;
            $gateid = $level->id;
            Gate::define($gate, function (User $user) use ($gateid) {
                return $user->checkLevel($gateid);
            });
        }

    }
}

如果我在运行第一次迁移“php artisan migrate”时留下这样的代码,我会收到以下错误: 未找到基表或视图:1146 表 'laravelporttail.levels' 不存在 (SQL: select * from levels)

如果我在引导内注释我的代码,则迁移工作。 之后我可以为数据库播种 然后在启动中取消注释我的代码。

知道如何在没有此迁移错误以及注释和取消注释我的代码的情况下做到这一点。

【问题讨论】:

  • 知道我用 Schema 和 If 语句解决了我的问题。 if(Schema::hasTable('levels')){ ...

标签: laravel migration laravel-artisan


【解决方案1】:

您可以定义单个 Gate,将模型查询推迟到迁移之前。

       $this->registerPolices();

        Gate::define('level', function (User $user, $gate) {
            $level = Level::where('gate', $gate)->firstOrFail();
            return $user->checkLevel($level->id);
        });

门的用途会有所不同。例如在您的路线中:

if( Gate::allows('level', 'example-level') ){
    echo 'You are in this level';
} else {
    echo 'You are not in this level';
}

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 2017-11-29
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 2016-07-08
    • 2017-04-18
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多