您好,我创建了一个只存储电话号码数字的修改器。这是我的配置文件模型中的代码。
public function setPhoneAttribute($phone)
{
$this->attributes['phone'] = preg_replace("/[^0-9]/","",$phone);
}
这在我创建新记录时有效,但如果我更新记录,它就不起作用。我的问题是如何在创建和更新时执行 Mutator?
这是我在 Controller 中更新和创建的方式:
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;
}
}
最佳答案
这是发生了什么:
Auth::user()->profile()->create($request->all())
在您的关系上调用 create
方法(HasOneOrMany
).然后,此方法创建一个相关模型的新实例。这很重要,因为显然只有在通过模型创建记录时才使用属性修改器。
然而,关系对象没有任何update
方法。 (拥有一个也没有意义......)。所以发生的事情是,当你执行 Auth::user()->profile()->update($request->all())
时。 update
调用 get 被代理到查询生成器实例(匹配关系)。这导致类似这样的事情被执行:
UPDATE profiles SET foo = 'bar' WHERE [relationship conditions]
它根本不使用该模型。因此,增变器不起作用。
相反,您必须在实际相关模型上调用 update
方法。您可以通过将关系作为属性调用来访问它,如下所示:
$saveToDatabase = Auth::user()->profile->update($request->all());
// ^^
// no parentheses
如果正确注入(inject)了 Profile
模型,您实际上也可以只使用它:
public function update(Profile $profile, ProfileRequest $request)
{
// Save to database
$saveToDatabase = $profile->update($request->all());
return $saveToDatabase;
}
关于php - Laravel 5 修改器仅在我创建记录而不是更新记录时起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29306890/