Được đăng ban đầu @ https. // mã và triển khai. com truy cập và tải xuống mã mẫu. https. // mã và triển khai. com/blog/laravel/xóa-record-in-laravel-8
Trong bài đăng ngắn này, tôi sẽ chia sẻ các phương pháp đơn giản để xóa các bản ghi trong Laravel 8 với các ví dụ
Xóa ví dụ
Xóa một lần với trình tạo truy vấn Laravel
DB::table('posts')->where('id', 1)->delete();
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Xóa nhiều lần với trình tạo truy vấn Laravel
DB::table('posts')->whereIn('id', [2, 4])->delete();
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Xóa một lần với Laravel hùng hồn
Post::where('id', 1)->delete();
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Xóa nhiều lần với Laravel hùng hồn
Post::whereIn('id', [2, 4])->delete();
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Đó là nó. Tiếp theo, chúng tôi sẽ triển khai trong ví dụ về bộ điều khiển của chúng tôi
Xóa thực hiện
mã điều khiển
/** * Remove the specified resource from storage. * * @param \App\Models\Post $post * @return \Illuminate\Http\Response */ public function destroy(Post $post) { $post->delete(); return redirect()->route('posts.index') ->withSuccess(__('Post delete successfully.')); }
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Mã lộ trình
Route::resource('posts', PostsController::class);
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
mã lưỡi
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Delete Record in Laravel 8 - codeanddeploy.com</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div class="container mt-5"> @if(Session::get('success', false)) <?php $data = Session::get('success'); ?> @if (is_array($data)) @foreach ($data as $msg) <div class="alert alert-success" role="alert"> <i class="fa fa-check"></i> {{ $msg }} </div> @endforeach @else <div class="alert alert-success" role="alert"> <i class="fa fa-check"></i> {{ $data }} </div> @endif @endif <table class="table table-striped" id="users-table"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Description</th> <th scope="col">Body</th> <th scope="col">Delete</th> </tr> </thead> <tbody> @foreach($posts as $post) <tr> <td>{{$post->title}}</td> <td>{{$post->description}}</td> <td>{{$post->body}}</td> <td> <form method="post" action="{{route('posts.destroy',$post->id)}}"> @method('delete') @csrf <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </td> </tr> @endforeach </tbody> </table> </div> </body> </html>
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Tôi hy vọng hướng dẫn này có thể giúp bạn. Vui lòng truy cập tại đây https. // mã và triển khai. com/blog/laravel/delete-record-in-laravel-8 nếu bạn muốn tải mã này