自动附加到 Laravel 5 中的枢轴 table

Automaticlly attach to pivot table in Laravel 5

我目前有一个用户与组的关系 (ManyToMany),其中包含一个枢轴 table group_user。我希望用户能够创建一个群组,但是一旦创建了群组,我该如何让创建者成为该群组的成员?

目前我有

我的支点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();
        });

我的群组table(群组):

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

我的用户table(用户):

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

我当然有以下模型:User.php

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

Group.php

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

我应该在控制器中编写什么创建函数,以便当用户创建组时,他自动成为该组的成员(自动建立枢轴关系)?

参见 attach() 和 detach()。

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

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

该用户的多个群组:

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

这应该有效,确保您实施验证等。

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');

    }

还要确保添加:

use App\Group;