Hi I am studying laravel. I use Eloquent ORM delete method but I get a different result.Not true or false but null. I set an resource route and there is a destroy method in UsersController.

public function destroy($id){

  $res=User::find($id)->delete();
  if ($res){
    $data=[
    'status'=>'1',
    'msg'=>'success'
  ];
  }else{
    $data=[
    'status'=>'0',
    'msg'=>'fail'
  ];
  return response()->json($data);

但我总是得到一个响应{"status":"0","msg":"failed"},数据库中的记录被删除.

Then I use dd($res) .It shows null in the page.

但我从课程中了解到,它返回布尔值true或false.

我的代码有错误吗?

Can you tell me some other method that I can get a boolean result when I delete data from database?

推荐答案

Before delete , there are several methods in laravel.

User::find(1)User::first()返回一个实例.

User::where('id',1)->getUser::all()返回实例的集合.

call delete on an model instance will returns true/false

$user=User::find(1);
$user->delete(); //returns true/false

对实例集合调用delete将返回一个数字,该数字表示已删除的记录数

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

Laravel相关问答推荐

Laravel-如何按第三表关系对数据进行分类

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

用Laravel Filament创建变形组件

当两个外键都在同一个表上时创建直通关系

使用 Laravel 计算页面浏览量

Laravel:子文件夹中的 lang 文件

Eloquent的条件过滤器

刚安装 Lumen 并得到 NotFoundHttpException

laravel:如何在 Eloquent Query 中使用 LOWERCASE 函数?

Laravel - 如何恢复本地存储符号链接并刷新

在 Laravel 中下载后如何重定向?

中间件中的 Laravel 依赖注入

Laravel Eloquent:计算总价的最佳方法

Auth 在 Laravel Tinker 中不起作用

Laravel/Lumen 中两列之间的 SQL

如何在 laravel 中解码 Json 对象并在 laravel 中应用 foreach 循环

Laravel 不活动时间设置

将值插入隐藏输入 Laravel Blade

如何在特定项目中禁用初始化 JS/TS 语言功能?

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500