0
votes

i want to show checked state from database, when i adding {{ $mod->hasAnyUnit($unit->kd_unit)?'checked':'' }} on view, i got error

i have units table, like a role table:

-------------------
id | kd_unit | name
-------------------
1  | 01      | A
2  | 02      | B
2  | 03      | C
-------------------

And 2nd is rs table, like a users table:

-------------------
id | kd_rs| name
-------------------
1  | 01   | ASD
2  | 02   | ZXC
-------------------

And 3rd is mod table, like a role_user:

-------------------
id | kd_rs| kd_unit
-------------------
1  | 01   | 01
2  | 01   | 02
3  | 01   | 03
-------------------

My Model from mod table:

class TManagerOnDuty extends Model
{
    public function units() {
        return $this->belongsToMany('App\Unit', 'kd_unit', 'kd_unit');
    }

    public function hasAnyUnits($units) {
        return null !== $this->units()->whereIn('kd_unit', $units)->first();
    }

    public function hasAnyUnit($unit) {
        return null !== $this->units()->where('kd_unit', $unit)->first();
    }
}

My Controller:

class ManagerOnDutyController extends Controller
{
  public function edit($kd_rs)
    {
        $units = Unit::orderBy('nm_unit', 'asc')->where('is_active', true)->get();
        $mod = TManagerOnDuty::where('kd_rs', $kd_rs)->get(); 
        return view('layouts.manageronduty.edit')->with([
            'mod'   => $mod,
            'units' => $units,
            'kd_rs' => $kd_rs
        ]);
    }
}  

My view:

@foreach($units as $unit)
    <div class="custom-control custom-checkbox mb-3">
        <input name="unitRS[]" value="{{$unit->kd_unit}}" {{ $mod->hasAnyUnit($unit->kd_unit)?'checked':'' }} id="customCheck{{$unit->kd_unit}}" class="custom-control-input" type="checkbox">
        <label class="custom-control-label" for="customCheck{{$unit->kd_unit}}">{{$unit->nm_unit}}</label>
    </div>
@endforeach

My error: enter image description here

My expected: enter image description here

1
What error are you receiving?xyz
wait, i will added my error pictureFenz
@Fenz check what are you getting in $mod by doing dd($mod);Prashant Deshmukh.....
@PrashantDeshmukh..... this is result for dd($mod) dd-imageFenz

1 Answers

1
votes

Try this one

$mod = TManagerOnDuty::where('kd_rs', $kd_rs)->first();

in your controller as get returns the set of object and you can not call your hasAnyUnit() from that set so first call a single object from you query and than chained it with hasAnyUnit()