'Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php)

I got an Error message Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php) when I'm trying to create a checkbox for the edit form page

my controllers

public function edit(Employeejadwalpiket $Employee, $id)
{
    $employee = Employee::all();
    $jadwalpiket = Jadwalpiket::all();
    $data = Employeejadwalpiket::with('employees','jadwalpiket')->find($id);

    return view('jadwalpiket.editemployeepiket', compact('Employee','employee','jadwalpiket','data'));

}

my view

<div class="col-xs-12 col-sm-12 col-md-12">
                        <div class="form-group">
                        <strong>Pilih Tugas :</strong>
                        <div class="form-check">
                            @foreach ($jadwalpiket as $j)
                                <label class="form-check-label">
                                <input class="form-check-input" type="checkbox" name="jadwalpiket_id[]" value="{{ $j->id }}" @if (count($Employee->jadwalpiket->where('id', $j->id)))
                                    checked
                                @endif>

                                    {{ $j->jadwal_piket }}&emsp;&emsp;
                                </label>
                                @endforeach
                            </div>
                        </div>
                    </div>

my web.php

Route::get('/editemployeepiket/{id}',[EmployeejadwalpiketController::class, 'edit'])->name('editemployeepiket'); 
Route::post('/upemployeepiket/{id}',[EmployeejadwalpiketController::class, 'update'])->name('upemployeepiket');

please help me to fix it..



Solution 1:[1]

Change this line

@if (count($Employee->jadwalpiket->where('id', $j->id))) checked @endif>

to

@if ($Employee->jadwalpiket()->where('id', $j->id)->count()) checked @endif>

If you use you use the query builder instead of the instance, you will avoid the error.

In all cases, you should do it differently and not call everything multiple times in your controller.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 N69S