drn5375 2017-11-05 10:58
浏览 305
已采纳

Laravel:如何验证模型是否已更改

Is there a simple way for the Eloquent save method to check if a row has actually changed? Something like affected_rows for Eloquent?

The only workaround that I found was from Laravel Eloquent update just if changes have been made to do:

$user = Auth::user();

$timestamp = $user->updated_at;

$user->title = $request->input('title');
....

$user->save();

if($timestamp == $user->updated_at){
   // row was not updated.
}

But is this possible to find this out shorter, without the need of a $timestep variable and the check? I don't want to repeat that logic in every controller.

I am looking for something like this:

$user = Auth::user();

$user->title = $request->input('title');
....

if($user->save()){
   // row was updated.
}

But this does not work since $user->save returns true in both cases. Is there another way?

  • 写回答

3条回答 默认 最新

  • doutui2883 2017-11-05 11:03
    关注

    First of all instead of:

    $user->save
    

    you should rather use:

    $user->save();
    

    And to verify if anything was changes in latest Laravel you can use:

    if ($user->wasChanged()) {
        // do something
    }
    

    but be aware this is as far as I remember in Laravel 5.5

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记