Laravel 5 mutators only work when I create a record and not when I update a record

后端 未结 2 1304
终归单人心
终归单人心 2020-12-16 00:24

Hi I have created a mutator to only store digits on my phone numbers. Here is my code in my Profile Model.

public function setPhoneAttribute($phone)
{
    $t         


        
相关标签:
2条回答
  • 2020-12-16 00:45

    Using this code instead of your code

    $saveToDatabase = Auth::user()->profile->update($request->all());
    
    0 讨论(0)
  • 2020-12-16 00:49

    Here's what's happening:

    Auth::user()->profile()->create($request->all()) calls the create method on your relationship (HasOneOrMany). This method then creates a new instance of the related model. This is important because obviously attribute mutators are only used when the record is created through the model.

    However the relationship object doesn't have any update method. (It also wouldn't make sense to have one...). So what's happening instead is, when you do Auth::user()->profile()->update($request->all()). The update call get's proxied off to a query builder instance (that matches the relationship). This results in something like this being executed:

    UPDATE profiles SET foo = 'bar' WHERE [relationship conditions]
    

    It doesn't use the model at all. Therefore the mutator doesn't work.

    Instead you have to call the update method on the actual related model. You can access it by just calling the relation as a property like this:

    $saveToDatabase = Auth::user()->profile->update($request->all());
    //                                    ^^
    //                               no parentheses
    

    If the Profile model is injected correctly you actually might also just use that though:

    public function update(Profile $profile, ProfileRequest $request)
    {
        // Save to database
        $saveToDatabase = $profile->update($request->all());
        return $saveToDatabase;
    }
    
    0 讨论(0)
提交回复
热议问题