How to reload/refresh model from database in Laravel?

前端 未结 5 1147
既然无缘
既然无缘 2020-12-14 05:39

In some of my tests, I have a user model I have created and I run some methods that need to save certain attributes. In rails, I would typically call something like us

5条回答
  •  不知归路
    2020-12-14 06:08

    I believe @Antonio' answer is the most correct, but depending on the use case, you could also use a combination of $model->setRawAttributes and $model->getAttributes.

    $users = User::all();
    
    foreach($users as $user)
    {
        $rawAttributes = $user->getAttributes();
    
        // manipulate user as required 
        // ..
        // Once done, return attribute state
    
        $user->setRawAttributes($rawAttributes);
    }
    

    The primary downside to this is that you're only "reloading" the data attributes, not any relationships you've altered, etc. That might also be considered the plus side.

    EDIT

    As of L5 - fresh() is the way to go

提交回复
热议问题