I am new to Laravel. Here i want to delete a object from database but it is not working. Why this happend?
is there something wrong?
@foreach ($todo as $item)
<tr>
<td style="border: 2px solid black;">{{ $loop->iteration }}</td>
<td style="border: 2px solid black;">{{ $item->todo }}</td>
<form action="">
@csrf
<td style="border: 2px solid black;"><button style="background-color: green;" type="submit">Selesai</button></td>
</form>
<form action="">
@csrf
<td style="border: 2px solid black;"><button style="background-color: yellow;" type="submit">Ubah</button></td>
</form>
<form action="{{ route('todo.destroy', $item) }}" method="POST">
@csrf
@method('delete')
<td style="border: 2px solid black;"><button style="background-color: red;" type="submit">Hapus</button></td>
</form>
</tr>
@endforeach
my controller:
public function store(Request $request)
{
// dd($request->all());
$validated = $request->validate([
'todo' => 'required|string|max:255',
]);
Todo::create($validated);
return redirect(route('todo.index'));
}
public function destroy(ToDo $toDo)
{
$toDo->delete();
return redirect(route('todo.index'));
}
4
Answers
Are you sure you’re getting the right model in your destroy function?
To make sure the object is valid, I think you need put the id and then delete by id. Example:
It looks like you are trying to delete it from a collection, but i think you want to delete it with the builder function. Please make sure you are handeling the call on the correct object.
For collections you could use the function forget
$toDo->forget();
update the form to pass the
id
of the model you want to delete.in your controller’s delete you can call
dd($toDo)
to check if the model is the one you expect.