odd one here. I have a table with a number of columns (unusual, eh?) and am creating a row via an Eloquent model in Laravel (v9). Here is a snippet of the code
while ($i <= $numrecs - 1) {
// if the qty is non-zero then we want to store it
if ($qtys[$i] != "") {
$itemrec = MyItem::create([
'user_id' => Auth::id(),
'item_type_id' => $ids[$i],
'my_property_room_id' => 5,
'my_property_id' => session('g_my_property_id'),
'name' => $names[$i],
'qty' => $qtys[$i],
'comments' => $comments[$i],
'client_id' => 0,
'version' => 1,
'date_effective_from' => now(),
'status' => 'ACTIVE'
]);
See that column my_property_room_id? Well for some reason that is always being stored with a null value in MySQL irrespective of what value I pass through (whether in a variable or as in this last ditch attempt to ensure that a value is actually being passed - in this case 5).
I can send a query to MySQL such as this
update my_items set my_property_room_id = 5 where user_id=6;
and the column holds the value 5 directly afterwards - so it's not a problem with e.g. foreign key violations.
All the other column settings being sent into the Eloquent model are stored as expected.
Scratching my head as to the possible causes here - no error messages being send back to the browser and the expected number of records are being written - just with this one column remaining unfilled.
Anyone got any thoughts on what might be the cause?
Thanks in advance, jeremy
CodePudding user response:
You also have to add that property to the $fillable
array of the Modelclass.
// app/Models/MyItem.php
protected $fillable = ['my_property_room_id'];
Alternatively, you can just do:
// app/Models/MyItem.php
protected $guarded = [];
Note The last option should only be used if you're not going to be mass assigning user input, so that you don't suffer injection attacks.