phplaravellaravel-bladecrud

How to delete data properly?


This is my delete button

              <!-- Hapus Data -->
              <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-     target="#exampleModal">
                Hapus
              </button>

              <!-- Modal -->
              <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalLabel"> Apakah anda yakin ingin menghapus data? </h5>
                      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>                        
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                      <a href="/deletedata/{{$row->id_pegawai}}" type="button" class="btn btn-primary">Ya</a>
                    </div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          @endforeach
        </tbody>
      </table>
    </div>
  </div>

I try to make CRUD using laravel. When i try to delete the third data, but the deleted data is first data. So i deleted data not what i want to delete

this is my controller

public function deletedata($id_pegawai){

        $post = Employee::where('id_pegawai',$id_pegawai)->first();
        if ($post != null) {
            $post->delete();
            return redirect('pegawai')->with('success', 'Data berhasil dihapus!');
    }

Solution

  • Eloquent provides multiple ways to do it. Here are some examples:

    1 - Using a model instance

    $employee = Employee::find($id);
    $employee->delete();
    

    2 - Delete using a where statement

    Employee::where('column', $value)->delete();
    

    This is useful in a situation where you have to delete one or more rows, not necessarily knowing their primary keys (but it could be used as well).

    3 - Using destroy method

    Employee::destroy($id);
    

    This will also remove many rows at once, if you pass them like

    Employee::destroy($id1, $id2, $id3 /* and so on...*/);
    

    or

    Employee::destroy(collect([$id1, $id2, $id3]));
    

    Font: https://laravel.com/docs/10.x/eloquent#deleting-models