add user in group according to his id

Viewed 20

I'm trying to add user in group that I've created according to id of the group, but when I add a user, he goes in all other group.

view and store function

`

public function groupeview(Request $request, $id){        

        
        $groupuser=Groupuser::where('groupuserid', Auth::id())->get();

        return view('groupeview')->with([            
            'groupuser'=> $groupuser
        ]);
    }  
    
    public function contactstoregroupe(Request $request){
        $request->validate([
            "name"=>"required",
            "email"=>"required",
            "number"=>"required",
        ]);

        Groupuser::create([
            "groupuserid"=>Auth::id(),
            "name"=>$request->name,
            "email"=>$request->email,
            "number"=>$request->number,
        ]);

        $groupe=Groupe::where('groupid',Auth::id())->get();
        return view('groupe')->with([
            'groupe'=> $groupe
        ]);
    }

`

1 Answers

I think you may doing it in a wrong way, Usually there are groups and there are users, each user can be belogns to one or more group and each group can hold one or more users, this is what group means, if what I described is your real purpose you may want to read about Many-To-Many relation.

In shortand you should create three tables, users, groups and user_groups table, the user_groups table should have two fields, user_id and group_id that points to users and groups tables, now when you desire to join user to group X you just insert the user id with the group id to the user_groups table, Laravel supports this kind of relation.

In your code your'e attaching to GroupUser the id of the user instead of both, so basicaly you should have three models:

User::class
Group::class
UserGroup::class

When you are creating the relation of user and group you should insert both group id and user id, the other fields needed to be in the user table and not in the relation table.

This answer based on your question description, but when I'm looking your code you may want to do something else, means create group belongs to user so the problem is in this line:

$groupe=Groupe::where('groupid',Auth::id())->get();

You should do as you did in view method:

$groupuser=Groupuser::where('groupuserid', Auth::id())->get();
Related