Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ethor's avatar
Level 1

Laravel fill with custom query fields

Prior Laravel 6 when i filled a model using a raw query, fields created in this query were assigned using the fill function even though the model does not have these fields in the database. When i upgraded from Laravel 5.8 this is no longer working. Is there any workaround for this?

Code example:

   $sql = "SELECT SUM(S.amount) AS total_amount, SI.* [...]"
   $data = \DB::select($sql)

   $collection = [];
		
   foreach($data as $row) {
      $item = new Item(); // Extends Eloquent Model
      $item->fill((Array) $row);
      $item->id = $row->id;
   	
      $collection[] = $item;
   }
		
   return collect($collection);

In this case the attribute total_amount is missing, but it was there prior upgrading to Laravel 6.

0 likes
4 replies
s4muel's avatar

check your $fillable and/or $guarded property in the Item model

fill() only works for not guarded (and fillable) attributes. try adding total_amount to fillable

protected $fillable = ['total_amount']; //add to the rest of any existing attributes
ethor's avatar
Level 1

I have defined:

protected $guarded = ['id'];

In my Model, but I want to avoid fillable since it would contain a massive amount of fields due to many custom queries.

ethor's avatar
ethor
OP
Best Answer
Level 1

Alright, thank you s4muel for your help and pointing me to the right documentation.

I will resolve to this 'ugly' solution to fix this if anyone else has the same problem:

foreach($row as $key => $value) {
   $item->$key = $value;
}

Please or to participate in this conversation.