简体   繁体   中英

Use Gate in laravel

I have a Server . I need to prohibit editing the Server to those users who did not create it. But there is a problem, the Server may have many Users who can edit it. I put this in a separate database table ServerUserCreate where server_id and user_id are stored.

It doesn't suit me. Since there is no user_id column in the Server table, because a lot of users can recommend

Gate::define('server-edit', function (User $user, Server $server) {
    return $user->id === $server->user_id;
});

I somehow need to compare

ServerUserCreates->server_id === $server->id || Auth::user()->id === ServerUserCreate->user_id

And if they are equal, then access is open. But I don't know how to do it in Gate at all

ServerUserCreate table

Schema::create('server_user_creates', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->id();
    $table->unsignedBigInteger('server_id');
    $table->unsignedBigInteger('user_id');
    $table->index('server_id', 'suc_server_idx');
    $table->index('user_id', 'suc_user_idx');
    $table->foreign('server_id', 'suc_server_fk')->on('servers')->references('id');
    $table->foreign('user_id', 'suc_user_fk')->on('users')->references('id');
    $table->timestamps();
});

Considering you have a relationship defined as

public function servers()
{
    return $this->hasMany(ServerUserCreate::class);
}

in the Server model, you can simplify your Gate definition a bit further by adding a WHERE condition to the relationship query.

exists() will return a boolean, so that's perfect for your use case.

Gate::define('server-edit', function (User $user, Server $server) {
    return $server->servers()->where('user_id', $user->id)->exists();
});

You could also use count() instead of exists() . In PHP, if you cast a number as a boolean, 0 is false, and the rest is true.

Gate::define('server-edit', function (User $user, Server $server) {
    return $server->servers()->where('user_id', $user->id)->count();
});

I was able to figure out the problem myself. Maybe it will help someone, here are my solutions

Gate::define('server-edit', function (User $user, Server $server) {
    $ServerUsers = $server->servers()->get();
    foreach ($ServerUsers as $ServerUser) {
        if ($ServerUser->server_id === $server->id && $ServerUser->user_id === $user->id) {
            return Response::allow();
        }
    }
    return Response::deny();
});
if (! Gate::allows('server-edit', $server)) {
    abort(403, 'Stop Stop!');
}

Server Model

public function servers()
{
    return $this->hasMany(ServerUserCreate::class);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM