2

I have business and profile models in my Laravel app. A business hasOne profile. 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

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. I am getting an error when it updates the profile model stating:

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. It looks like updating related Models does not adhere to the mass assignment rules built into Laravel. Could someone advise how to fix this?

InvalidSyntax
  • 9,131
  • 20
  • 80
  • 127

2 Answers2

3

You can either add $fillable to your model or use $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()); to $business->profile->update($request->all());.

Alex
  • 3,719
  • 7
  • 35
  • 57
  • the `$fillable` variable in both models are populated with the correct fields (and they dont include _token or _method) which is why I don't get how its trying to update those fields. – InvalidSyntax Apr 26 '17 at 00:40
  • I don't think I need to use `only()` if the `$fillable` is defined in my Models – InvalidSyntax Apr 26 '17 at 00:41
  • 1
    `$business->profile()->update($request->all());` will immediately produce and perform an SQL update query, rather than updating the model and then saving the changes to the database. The latter will adhere to the `$fillable` rules, the former will not. – fubar Apr 26 '17 at 01:20
  • Yes, you can just change `profile()` to `profile` to make it work. – Alex Apr 26 '17 at 01:30
0

I wanted to make use of $fillable on my Models and not have to manually state which columns are to be populated.

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 :-)

InvalidSyntax
  • 9,131
  • 20
  • 80
  • 127