Laravel 5 mutators 只在创建记录时有效,而更新记录时无效

12

嗨,我创建了一个变异器,用于仅在我的电话号码上存储数字。这是我在个人资料模型中的代码。

public function setPhoneAttribute($phone)
{
    $this->attributes['phone'] = preg_replace("/[^0-9]/","",$phone);
}

当我创建一个新记录时,这个方法起作用了,但如果我更新记录它就不起作用了。我的问题是如何在创建和更新时都执行这个Mutator?

这是我在控制器中进行更新和创建的方式:

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\ProfileRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Profile;

class ProfileController extends Controller {

    public function create(ProfileRequest $request)
    {
        // Check if the user does not have a profile yet
        if(!Auth::user()->profile()->first()){

            // Save to database
            $saveToDatabase = Auth::user()->profile()->create($request->all()); 

            return $saveToDatabase;
        }
    }

    public function update(Profile $profile, ProfileRequest $request)
    {

        // Save to database
        $saveToDatabase = Auth::user()->profile()->update($request->all());

        return $saveToDatabase;
    }
}

请问您能否编辑您的问题并添加代码,以展示如何更新/创建记录? - lukasgeiter
2个回答

23

以下是发生的情况:

Auth::user()->profile()->create($request->all()) 调用你关系(HasOneOrMany)上的 create 方法。该方法会创建一个相关模型的新实例。这很重要,因为显然只有通过模型创建记录时才会使用属性修改器

然而,关系对象没有任何update方法。(也没有意义...)。所以,当你执行Auth::user()->profile()->update($request->all())时,update调用会被代理到与关系相匹配的查询构建器实例中。这会导致执行类似以下内容的代码:

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

它根本没有使用模型。因此变异器不起作用。

相反,您需要在实际相关模型上调用update方法。您可以通过将关系作为属性调用来访问它,如下所示:

$saveToDatabase = Auth::user()->profile->update($request->all());
//                                    ^^
//                               no parentheses
如果Profile模型被正确注入,你实际上也可以直接使用它:
public function update(Profile $profile, ProfileRequest $request)
{
    // Save to database
    $saveToDatabase = $profile->update($request->all());
    return $saveToDatabase;
}

谢谢!这很有道理。这解决了我的问题:$saveToDatabase = $profile->update($request->all()); - OsvyG

1
使用这段代码代替你的代码。
$saveToDatabase = Auth::user()->profile->update($request->all());

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