Delete Records
优质
小牛编辑
128浏览
2023-12-01
我们可以使用delete方法使用DB facade删除记录。 delete方法的语法如下表所示。
Syntax | int delete(string $ query,array $ bindings = array()) |
Parameters |
|
Returns | int |
Description | 对数据库运行delete语句。 |
例子 (Example)
Step 1 - 执行以下命令以创建名为StudDeleteController的控制器。
php artisan make:controller StudDeleteController --plain
Step 2 - 成功执行后,您将收到以下输出 -
Step 3 - 将以下代码复制到文件
app/Http/Controllers/StudDeleteController.php
app/Http/Controllers/StudDeleteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudDeleteController extends Controller {
public function index(){
$users = DB::select('select * from student');
return view('stud_delete_view',['users'=>$users]);
}
public function destroy($id) {
DB::delete('delete from student where id = ?',[$id]);
echo "Record deleted successfully.<br/>";
echo '<a href = "/delete-records">Click Here</a> to go back.';
}
}
Step 4 - 创建一个名为的视图文件
resources/views/stud_delete_view.blade.php并在该文件中复制以下代码。
resources/views/stud_delete_view.blade.php
<html>
<head>
<title>View Student Records</title>
</head>
<body>
<table border = "1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Edit</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href = 'delete/{{ $user->id }}'>Delete</a></td>
</tr>
@endforeach
</table>
</body>
</html>
Step 5 - 在app/Http/routes.php添加以下行。
app/Http/routes.php
Route::get('delete-records','StudDeleteController@index');
Route::get('delete/{id}','StudDeleteController@destroy');
Step 6 - 输出将如下图所示。
Step 7 - 单击删除链接以从数据库中删除该记录。 您将被重定向到一个页面,您将在该页面中看到如下图所示的消息。
Step 8 - 单击“ Click Here链接,您将被重定向到一个页面,您将看到除已删除记录之外的所有记录。