在Laravel Model中更新数据后如何返回更新后的数据?

4
我有一个名为Driver的模型,它拥有以下列:name, branch, status_id, etc.。更新数据是可以正常工作的,但我的问题是如何返回更新后的数据?
我已经尝试过以下代码,但它只返回一个boolean值,在控制台中会报错:

The Response content must be a string or object implementing __toString(), "boolean" given.

public function updateStatus(Driver $driver)
{
    return $driver->update($this->validateStatus());
}

public function validateStatus()
{
    return $this->validate(request(), [
        'status_id' => 'required|min:1|max:3'
    ]);
}

我希望它可以返回驱动程序的所有列。

我访问了这个链接,但没有得到帮助。有人知道怎么做吗?


嘿,你能不能帮我检查一下我的答案?我在控制器中直接解决了模型助手的问题,你可以返回结果。 - Kamlesh Paul
5个回答

11
您可以使用tap()助手,该助手将在更新后返回更新后的对象,如下所示:
return tap($driver)->update($this->validateStatus());

在此处了解更多:Tap助手


4

应当以对象的形式而不是布尔类型返回

public function updateStatus(Driver $driver)
{
   $driver->update($this->validateStatus());
   return $driver;// first way
   // return tap($driver)->update($this->validateStatus()); //second way
}

public function validateStatus()
{
    return $this->validate(request(), [
        'status_id' => 'required|min:1|max:3'
    ]);
}

1
希望能有一行代码解决这个问题 :) 但是,这个方法也可以。谢谢。 - charles

3

这对我很有效

   $notify = tap(Model::where('id',$params['id'])->select($fields))->update([
            'status' => 1
        ])->first();

2

我认为不需要任何模型辅助

控制器 中,您可以这样做

$driver = Driver::find(1);
$driver->name = "expmale";
$driver->save();

return $driver;

或者其他方式
$driver = Driver::find(1);
$driver->update([
      'name'=> "expmale"
      ]);

return $driver;

这个策略不会返回更新后的名称,因为你在更新之前使用了查找方法,所以它只会返回更新前的数据。 - Nazmus Shakib

0

我知道这个问题已经有答案了,但理想情况下,你不应该使用 update 方法。它只是一个模型帮助方法,没有什么实际意义。在内部,它执行了我下面提到的操作,但返回了 save() 的结果。

你应该像这样做:

if ($driver->fill($this->validateStatus)->save()) {
    return $driver;
}

throw new \RuntimeException('Update failed, perhaps put something else here);

你将会遇到一个问题,那就是大多数答案都没有检查模型是否真的被更新,所以在后续的过程中,当它报告已经更新但实际上并没有更新数据库时,你会遇到问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接