roles icon indicating copy to clipboard operation
roles copied to clipboard

Multiple Owners - Many-to-Many

Open nikeshbhagat opened this issue 9 years ago • 1 comments

Hello,

So, first, I really like what you've done here, but I'm a bit new to Laravel and I have a question regarding using your setup to check for ownership when there is a possibility that many users 'own' a record.

For example, I have a table called 'inventories' and I want to allow the creator of an inventory to update and delete any inventory they create, but multiple users can have that ability.

Scenario:

User 1 and User 2 are admins. User 1 creates an inventory, user 2 wants to delete it. Both are owners of that inventory via a look-up table called 'inventory_user' so there is, potentially, a many-to-many relationship between users and inventories. There is not a 'user_id' column in the inventories table, but rather an inventory_user table that specifies, potentially, the 'many' users that own any particular inventory. So - I have an Inventory model AND and InventoryUser Model.

Question: How do I check if a user owns an inventory if it's possible for multiple users to own an inventory?

Just by typing this question I'm starting to think my setup is a little off, but nonetheless, is there a way to do:

if ($user->allowed('edit.articles', $article)) { // $user->allowedEditArticles($article)}

If $user is just one of many possible users who have this permission?

Hope my question is clear enough. If not, apologies.

Thanks in advance for any insight you can provide!

nikeshbhagat avatar Oct 07 '15 09:10 nikeshbhagat

Does not feel like that you realize this with permissions.

You should think about your schema and not the permission.

Schema::create('inventory_editors', function(Blueprint $table) {
    $table->increment('id');

    $table->integer('inventory_id', false, true);
    $table->integer('user_id', false, true);

    $table->foreign('inventory_id')->references('id')->on('inventory');
    $table->foreign('user_id')->references('id')->on('user');

    $table->unique(['inventory_id', 'user_id']);
});

and then add a new function to your Inventory model, public function editors() returning a collection of users allowed to edit this inventory. Simply check $inventory->editors()->contains(\Auth::user()); or very similar to this.

Read more about relations and how to set them up :)

Isfirs avatar Apr 08 '16 12:04 Isfirs