简体   繁体   中英

Edit page checkbox value from database

I have a table like below

id |    name    |   pic   |     level     |  team
1     John          3           user           
2     Ipsum         4           user           
3     Lorem         5          supervisor     
4     Dolor Amet    5           admin         
5     Amet                     manager        3,4
6     Diego         7           user          
7     Michael       5           supervisor    

I want to, as user id 5, show what team I can see in checkbox value and edit or change it in checkbox. I have tried, but it is error. User id 3 that has been checked also show again in not-checked value like this 截图

So the view is must be like ipsum(checked) and dolor (not checked) like 这张照片

Here is the blade view code

 @foreach($supervisor as $spv)          
    <div class="checkbox">
    @foreach($result as $res)
       @if($spv->id == $res->id)
         <label>
         <input type="checkbox" name="spv[]" value="{{ $spv->id }}" checked>{{ $spv->name }}
         </label>
       @else 
         <label>
         <input type="checkbox" name="spv[]" value="{{ $spv->id }}">{{ $spv->name }}

         </label>
      @endif
     @endforeach
   </div>
   @endforeach

Here's the controller code

$query = DB::table('users')->where('id',$id)->first();

$list=explode(',', $query->team);
$result = DB::table('users')->whereIn('id',$list)->get();

$supervisor = Users::where('level','supervisor')->orWhere('level','admin')->get();

Do you know where is the missing ?

You can try this:

In your controller compact the $list variable because it is the array of team id's:

$query = DB::table('users')->where('id',$id)->first();

$list=explode(',', $query->team);
$result = DB::table('users')->whereIn('id',$list)->get();

$supervisor = Users::where('level','supervisor')->orWhere('level','admin')->get();

return view('your-blade-view', compact('result', 'supervisor', 'list'));

And then In your blade :

 @foreach($supervisor as $spv)          
     <div class="checkbox">
         <label>
             <input type="checkbox" name="spv[]" value="{{ $spv->id }}" {{ ( in_array($spv->id, $list) ) ? 'checked' : '' }}>{{ $spv->name }}
         </label>
     </div>
 @endforeach

I hope it would helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM