php - Automaticlly attach to pivot table in Laravel 5 -


i have users groups relationship (manytomany) pivot table group_user. want user able create group once creating group, how make it, creator becomes member of group?

currently 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 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 write in controller when user creates group, automaticly becomes member of group (automaticlly make pivot relationship)?

this should work, make sure implement validation, ect.

public function store(request $request)     {         $group = group::create([ // <-- if names unique. if not, create fine         'name' => $request->get('name')         ]);         auth()->user()->groups()->attach([$group->id]);          return view('your.view');      } 

also make sure add:

use app\group; 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -