简体   繁体   English

Laravel不遵守相关模型更新的批量分配$可填充规则

[英]Laravel not adhering to Mass Assignment $fillable rules for related model update

I have business and profile models in my Laravel app. 我的Laravel应用中有businessprofile模型。 A business hasOne profile. 一家企业hasOne个人资料。 I've created a patch method form using the form builder to update my business and profile tables. 我已经使用表单构建器创建了一个补丁方法表单来更新我的业务表和个人资料表。

Blade

{!! Form::model($business, ['route' => ['business.edit.post', $business], 'method' => 'PATCH']) !!}
                @include('forms.business.edit')
{!! Form::close() !!}

BusinessController BusinessController

public function update(Request $request, $id)
{
    $business = Business::findOrFail($id);

    $business->update($request->all());
    $business->profile()->update($request->all());        

    return back()->withMessage('updated');
}

Now using a patch method will include a hidden field called _method along with the built in _token field for csrf protection. 现在,使用补丁方法将包括一个名为_method的隐藏字段以及用于csrf保护的内置_token字段。 I am getting an error when it updates the profile model stating: 更新profile模型时出现错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update `business_profiles` set `_method` = PATCH, `_token` = Zyxtxa88uUQKhaRQNY8k7qPu2N0i6o20dY4sUABk, `city` = Belfast where `business_profiles`.`business_id` = 107 and `business_profiles`.`business_id` is not null)

It appears to me its trying to update those hidden fields when it shouldn't. 在我看来,它试图在不应该更新那些隐藏字段的情况下进行尝试。 When commenting out the _ profile->update line the save works fine. 当注释_ profile->update行时,保存工作正常。 It looks like updating related Models does not adhere to the mass assignment rules built into Laravel. 看起来更新相关模型不符合Laravel中内置的质量分配规则。 Could someone advise how to fix this? 有人可以建议如何解决此问题吗?

You can either add $fillable to your model or use $request->only([]) . 您可以将$fillable添加到模型中,也可以使用$request->only([])

EDIT 编辑

Looks like the problem is you are updating through the relationship. 看起来问题在于您正在通过关系进行更新。 The simple fix, as you figured it out and as comments suggest, is to change $business->profile()->update($request->all()); 如您所见和注释所建议的,简单的解决方法是更改$business->profile()->update($request->all()); to $business->profile->update($request->all()); $business->profile->update($request->all()); .

I wanted to make use of $fillable on my Models and not have to manually state which columns are to be populated. 我想在我的模型上使用$fillable ,而不必手动声明要填充哪些列。

I altered my update method as follows: 我更改了更新方法,如下所示:

$business = Business::findOrFail($id);
$profile = $business->profile;

$business->update($request->all);
$profile->update($request->all);

I'm sure theres a smarter way to do this, but this will do for now :-) 我敢肯定,有一种更聪明的方法可以做到这一点,但这暂时就可以了:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM