in PegawaiController i use join to take nama_departemen from Departemen table
public function index()
{
$data_pegawai = Pegawai::join('departemens','pegawais.id_departemen','=','departemens.id')->paginate(5);
return view ('pegawai.index', compact('data_pegawai'));
}
public function destroy($id)
{
Pegawai::find($id)->delete();
return redirect()->route('pegawai.index')->with(['success'=> 'Item Berhasil Dihapus']);
}
in pegawai.index
@forelse ($data_pegawai as $item)
<tr>
<td class="text-center">{{ $item->nomor_induk_pegawai }}</td>
<td class="text-center">{{ $item->nama_pegawai }}</td>
<td class="text-center">{{ $item->nama_departemen }}</td>
<td class="text-center">{{ $item->email }}</td>
<td class="text-center">{{ $item->telepon }}</td>
@if($item->gender==0)
<td>Wanita</td>
@else
<td>Pria</td>
@endif
@if($item->status==0)
<td>Inactive</td>
@else
<td>Active</td>
@endif
<td class="text-center">
<form onsubmit="return confirm('Apakah Anda Yakin ?');" action="{{ route('pegawai.destroy', $item->id) }}" method="POST">
<a href="{{ route('pegawai.edit', $item->id) }}" class="btn btn-sm btn-primary">EDIT</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Hapus</button>
</form>
</td>
</tr>
@empty
<div class="alert alert-danger">
Data Pegawai belum tersedia
</div>
@endforelse
im trying to delete data with DELETE button. it said Call to a member function delete() on null but sometimes it work. i use the same code for delete button in departemen.index and it working fine. how to fix this?
2
Answers
Sometimes it’s working because the data is not deleted in that case it works. And when data is deleted and you are redirecting again that page then an error will throw as Call to a member function delete() on null.
To ignore this value you have to simply create a list view. when you are redirecting to the list view which contains all data which are not deleted
First, you need check if there is a record with that ID before trying delete it.
The best way to do it is typing the param.
In Controller:
In the route file you need change the param name from
$id
to$pegawai
.Laravel will check if the ID is valid before enter into the function.