0

i have two tables group(parent) and users(kid) . I can read data from each group but i want to show them inside a multiselect so i can remove or add more users to the group and update.

Group controller:

  public function edit($id)
   {
   //
   $group= Group::find($id);
   $users = User::where('group_id',$id)->get();


   return view('group.edit',compact('group','users'));
 }

 public function update(Request $request, $id)
 {
 $request->validate([
 'name'=> 'required',
 'group_id' => 'required|array',
 ]);

 $group = Group::find($id);
 $group ->name = $request->get('name');


       //something missing/wrong here

 $group->save();



 return redirect('/groups')->with('success', 'Group has been edited');
 }

User model:

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

Group model

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

edit view:

<form method="post" action="{{ route('groups.update', $group->id) }}">
    @method('PATCH')
    @csrf
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" name="name" value={{ $group->name }} />
    </div>
    <div class="form-group">
        <select name="group_id[]" id="users" class="form-control"  multiple>
            @foreach ($users as $user)
            <option value="{{$user->id}}">{{$user->name}}</option>
            @endforeach
        </select>
        </div>
    <a href="{{url()->previous()}}" class="pull-right btn btn-danger" >Cancel</a>
    <button type="submit" class="pull-right btn btn-primary" style="margin-right:5px;">Update</button>
  </form>

Database structure:

Groups table:

id
name

Users table:

id
name
email
group_id

Im using select2 package and this is what im trying to make :

https://ibb.co/Y8vWHpy.

Thanks

ZarkOs
  • 27
  • 11

2 Answers2

1

I think it will work

  $group = Group::find($id)->delete();
  $name= $request->input('name');
  $group_ids= $request->input('group_id')
    foreach($group_ids as $group_id){
      $group = new Group();
      $group ->name= $name;
      $group ->group_id= $group_id;
      $group->save();
   }
Zahid Hassan Shaikot
  • 1,066
  • 10
  • 18
0

hi it is working for me i hope its usefull for you IN EDIT

   $group= Group::find($id);
   $allUsers=['users'=>User::get()->pluck('name','id')];
   $users = User::where('group_id',$id)->pluck('id')->toArray();
   return view('group.edit',compact('group','users','allUsers'));

IN YOUR View

{!! Form::select("group_id[]",array_get($allUsers,'allUsers'),$users,["class"=>"form-control select2","multiple"=>'multiple']) !!}

And Finally in your Update

I Can not figure out what exactly happened but you will have users Id in your update