-
Notifications
You must be signed in to change notification settings - Fork 1.5k
The mass assignment doesn't work on nested fillable in the update #2619
-
Hi guys, I used fillable in my model and it works correctly when creating, and if a new attribute comes in the information that is not in the fillable list, it is not added to the document, but it is not like that in update, and this is annoying.
Is there a solution for it in the package? Or PR should be given?
Model User.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Jenssegers\Mongodb\Eloquent\Model; class User extends Model { use HasFactory; protected $fillable = [ "id", "first_name", "last_name", "username", "wallets" // this attribute is nested ];
demo:
image
My code for update:
$user = \App\Models\User::where('user_id', 1)->first(); $user->update(['wallets.balance'=>1000 , 'test'=>'blablabla']);
But no update is done in this way. :(
Now, if we do this using the code below, the update will be done, but we will lose the mass assignment feature, and a field that is not in the fillable list, such as test, will be added to the document.And also other fields are removed from the document and this is disastrous.
$user = \App\Models\User::where('id', 1)->first(); dd($user->fill(['wallets' => ['balance' => 1400, 'test' => 'blablabla']])->save());
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
I've created PHPORM-89 to track this internally. Please follow that ticket to get updates when we start implementing it.
Beta Was this translation helpful? Give feedback.
All reactions
-
I found the solution :). Fillable nested list should be defined like this.
protected $fillable = [ "wallets.balance", "wallets.wallet_id", "wallets.currency.code", "wallets.currency.symbol", ];
It works correctly in this way, but there is still a reason to worry if the data is defined like this, the undefined data is still stored in fillable:
$data = [ 'wallets.balance' => 2350, 'wallets.currency' => ['code' => 'IR', 'symbol' => 'IRT', 'sss' => ':)'] ]; $user = \App\Models\User::where('id', 8)->first(); $user->update($data);
To solve this problem, we need that converts nested arrays using dot like this:
$user = \App\Models\User::where('id', 8)->first(); dd($user->update(Arr::dot($data )));
// result
array:5 [▼ "wallets.balance" => 2350 "wallets.currency.code" => "IR" "wallets.currency.symbol" => "IRT" "wallets.currency.sss" => ":)" ]
In this way, it seems that the problem is solved and the wallets.currency.sss
field is ignored.. I will be happy if you suggest a better way.
In my opinion, the mass assignment nested place is empty in the document package and it is better to include it for more information.
Beta Was this translation helpful? Give feedback.