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();
});
2
Answers
I was able to figure out the problem myself. Maybe it will help someone, here are my solutions
Server Model
Considering you have a relationship defined as
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.You could also use
count()
instead ofexists()
. In PHP, if you cast a number as a boolean, 0 is false, and the rest is true.