如何正确删除数据?

问题描述 投票:0回答:1

这是我的删除按钮

              <!-- 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>

我尝试使用 laravel 进行 CRUD。当我尝试删除第三个数据时,但删除的数据是第一个数据。所以我删除的数据不是我想删除的

这是我的控制器

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!');
    }
php laravel laravel-blade crud
1个回答
0
投票

Eloquent 提供了多种方法来做到这一点。以下是一些示例:

1 - 使用模型实例

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

2 - 使用 where 语句删除

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

这在您必须删除一行或多行且不一定知道其主键的情况下非常有用。

3 - 使用

destroy
方法

Employee::destroy($id);

如果您像这样传递它们,这也会一次删除许多行

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.