Home > Back-end >  Use Gate in laravel
Use Gate in laravel

Time:01-12

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

CodePudding user response:

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

CodePudding user response:

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