Borni
Borni

Reputation: 169

Automaticlly attach to pivot table in Laravel 5

I currently have a Users to Groups Relationship (ManyToMany) with a pivot table group_user. I want the user to be able to create a group but once creating the group, how do I make it, that the creator becomes member of this group?

Currently I have

My Pivot Table (group_user):

Schema::create('group_user', function(Blueprint $table)
        {
            $table->integer('group_id')->unsigned()->index();
            $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');

            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->timestamps();
        });

My Groups table (groups):

Schema::create('groups', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        }); 

My Users table (users):

Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('name');
            $table->string('lastname');
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });

My models ofcourse have the following: User.php

public function groups() 
    {
        return $this->belongsToMany('App\Group');
    }

Group.php

public function users()
    {
        return $this->belongsToMany('App\User');
    }

What create function should I write in my controller so that when a User creates a Group, that he automaticly becomes member of this group (automaticlly make the pivot relationship)?

Upvotes: 0

Views: 868

Answers (2)

Pex
Pex

Reputation: 519

This should work, make sure you implement validation, ect.

public function store(Request $request)
    {
        $group = Group::create([ // <-- if names are unique. if not, then create is fine
        'name' => $request->get('name')
        ]);
        auth()->user()->groups()->attach([$group->id]);

        return view('your.view');

    }

Also make sure to add:

use App\Group;

Upvotes: 1

Bishal Paudel
Bishal Paudel

Reputation: 1956

See attach() and detach().

$user = User::find(1);
$user->groups()->attach(10); // pivot relationship of this user to group of id 1.

OR

$group = Group::find(10);
$user->groups()->save($group); 

For many groups of this user:

$user->groups()->sync(array(1, 2, 3));

Upvotes: 1

Related Questions