gvstavnev
8 months ago
122
10
Eloquent

Attach() on custom belongsToMany-Model

Posted 8 months ago by gvstavnev

Hi there.

Im relatively new to laravel – so I hope my question is worth asking.

In my current project I have users and folders. A folder can have many users and a user can have many folders. So I came up with the belongsToMany relation. Then, I wanted a model that handles the relation between user and folder, because I want to assign different roles to it. So I created the a membership model.

I will only show you the relevant code (I hope). So this is my code:

User.php

    public function folders() {
        return $this
            ->belongsToMany(Folder::class)
            ->using(Membership::class);
    }

Folder.php

    public function users() {
        return $this
            ->belongsToMany(User::class)
            ->using(Membership::class);
    }

My question is now, how to attach a folder to a user. Currently, when Im trying to call $user->folders or $user->folders()->attach($folder) I get the error folder_user' doesn't exist – ye because I want the membership table to handle this.

Kind Regards Gustav

Please sign in or create an account to participate in this conversation.