1
votes

I am very new to laravel. Learned how to create models, controllers, blog post with comments type of application and to take the learning further I am attempting to achieve:

Register user and simultaneously create a group for user. (There is a users table, a groups table & a user_group_relations table)

On the RegisterUsers.php provided by laravel:

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    //step 1:make a group with registered user email as group name
    //step 2:make a user_group_relations entry relating user with group

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

What is the best practice to do this? For step 2 the method will need to be accessed by other models as well, i am still unsure on how to share the method across models without causing static function errors.

You may be asking Why there is a user_group_relations table?

I know most people will be doing the belongsTo and hasMany relation method in the models or storing user_id json in groups table. The application needs to list the groups a user may be in (user can have many groups), this is why i thought a separate table to handle relations will be better.

Any help is greatly appreciated! Thank you!

2

2 Answers

0
votes

Try something like this. Frrst create the user and group

$user = $this->create($request->all()));
$group = new Group();

Depending on your relationship attach it to the user

$user->groups->attach($group);

Then fire the event

event(new Registered($user);
0
votes

i have done the following and it is working, but is this the best practice?

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    $user = $this->create($request->all());

    $group = new Group([
        'owner'         =>  $user->id,
        'group_name'    =>  $user->email,
        'group_info'    =>  null,
        'group_desc'    =>  null,
        'archive'       =>  false
    ]);

    $group->save();

    $usergrouprelationship = new UserGroupRelationship([
        'user'      =>  $user->id,
        'group'     =>  $group->id,
        'archive'   =>  false
    ]);

    $usergrouprelationship->save();

    event(new Registered($user));

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}