如何在 Laravel 5 中删除单条记录?
有多种方法可以实现。让我们测试一些示例,帮助我们删除 Laravel 中的单条记录。
假设我们创建了一个名为users的表,如下所示:
mysql> select * from users; +----+---------------+------------------+--------------+------------+------+ | id | name | email | password | address | age | +----+---------------+------------------+--------------+------------+------+ | 1 | Siya Khan | siya@gmail.com | hgfdv3vhjd | Xyz | 20 | | 2 | Rehan Khan | rehan@gmail.com | cskjg367dv | Xyz | 18 | | 3 | Rehan Khan | rehan@gmail.com | dshjgcv2373h | testing | 20 | | 4 | Rehan | rehan@gmail.com | abcd | vci4hn4f4 | 15 | | 5 | Nidhi Agarwal | nidhi@gmail.com | fjh99302v | abcd | 20 | | 6 | Ashvik Khanna | ashvik@gmail.com | 83bg44f4f | oooo | 16 | | 7 | Viraj Desai | viraj@gmail.com | ppsdkj39hgb2 | test | 18 | | 8 | Priya Singh | priya@gmail.com | chjbbvgy3ij | test123 | 20 | +----+---------------+------------------+--------------+------------+------+
示例 1
可以使用find()方法,它接受一个键值作为参数,并返回具有给定键作为主键的模型。delete()方法删除当前记录。以下示例演示如何使用这两个方法删除记录:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $userDetails = User::find(9); $deleteuser = $userDetails->delete(); if ($deleteuser) { echo "Record deleted from table successfully"; } else { echo "Error in Deletion"; } } }
输出
以上代码的输出如下:
Record deleted from table successfully
示例 2
可以在 where 子句中添加条件,以从表中删除记录,如下所示:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $deleteuser = User::where('id', '=', 11)->delete(); if ($deleteuser) { echo "Record deleted from table successfully"; } else { echo "Error in Deletion"; } } }
输出
以上代码的输出为:
Record deleted from table successfully
示例 3
还可以使用destroy()方法从表中删除记录。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $deleteuser = User::destroy(12);; if ($deleteuser) { echo "Record deleted from table successfully"; } else { echo "Error in Deletion"; } } }
输出
以上代码的输出为:
Record deleted from table successfully
示例 4
如果要一次删除多条记录,可以按如下所示操作:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $deleteuser = User::destroy([15,16,17]); if ($deleteuser) { echo "Record deleted from table successfully"; } else { echo "Error in Deletion"; } } }
输出
以上代码的输出为:
Record deleted from table successfully
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP