skip to Main Content

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


  1. Are you sure you’re getting the right model in your destroy function?

    Login or Signup to reply.
  2. To make sure the object is valid, I think you need put the id and then delete by id. Example:

    $toDo = ToDo::find($id);
    $toDo->delete();
    
    Login or Signup to reply.
  3. 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();

    Login or Signup to reply.
  4. update the form to pass the id of the model you want to delete.

    <form action="{{ route('todo.destroy', $item->id) }}" method="POST">
      @csrf
      @method('delete')
      <td style="border: 2px solid black;">
        <button style="background-color: red;" type="submit">Hapus</button>
      </td>
    </form>
    

    in your controller’s delete you can call dd($toDo) to check if the model is the one you expect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search