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

Paeolen's avatar

How to fill a model when request has too many fields?

Hi everyone,

I'd like to update my model. I validate my request first, but the problem is I have fields in it that are meant for another model update.

What is the best, most eloquent way to handle this?

Because when I try to fill my model with $request->all(), the Builder tries to add non-existent columns to db and I get an error.

In my model, I have guarded the id and the timestamps.

Thank you.

0 likes
8 replies
jlrdw's avatar

Need to see more code but it sounds like something is definitely set up wrong.

Paeolen's avatar
$model = Model::findOrFail($id);
$model->fill($request->all());
$model->save();
public $guarded = ['id', 'created_at', 'updated_at'];
SQLSTATE[42S22]: Column not found: 1054 Field 'OtherField' unknown in field list

The problem comes from my request having unrelated fields, because they are for another related model update.

One solution would be to filter the requests input to only get the relevant fields to my model, but I'm wondering if there's an eloquent way to do this, beacuse there are a lot of fields and might change in the future.

Paeolen's avatar

Ah, just found that if I use $fillable instead of $guarded, it works. Good to know, and now I think about it, it makes sense.

Snapey's avatar
Snapey
Best Answer
Level 122

the easiest way is to use $fillable instead of guarded and then you would not get the error.

next best is to use $request->only(['field1', 'field2']);

Use this instead of all and just the listed fields will be passed to the model

edit: you posted as i was typing one fingered on my Ipad!

1 like
digitaloutback's avatar

I generally use guarded because I have many tables with too many fields to list them in fillable (some are 30+ fields). To get round this I wrote a model function in my parent model class like this:

/**
 * Returns all writable fields for the model's table
 *
 * @return array
 */
public function getWritable()
{
    if (!empty($this->fillable))
        return $this->fillable;

    return collect(Schema::getColumnListing($this->getTable()))
        ->flip()
        ->except($this->guarded)
        ->keys()
        ->toArray();
}

And use in my controller like:

$model->update($request->only($model->getWritable()));

Not sure if this has many trade-offs and the getWritable() could be optimised but it's working fine for me.

Please or to participate in this conversation.