Search code examples
phplaravelmass-assignment

Laravel 5.2 Model $fillable gets ignored?


I have a simple Model IsolatedQuery which consists of a name and query field. I have defined those two fields in the $fillable property of the model. The IsolatedQueryController@store looks like this:

public function store(IsolatedQueryRequest $request)
{
    IsolatedQuery::insert($request->all());

    session()->flash('flash_message', 'Isolated Query succesvol opgeslagen');

    return redirect('iq');
}

For completeness, here is the Model's source (it is as little as I described it)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class IsolatedQuery extends Model
{
    protected $fillable = [
        'name',
        'query'
    ];
}

The IsolatedQueryRequest only requires both name and query to be filled with any value.

When calling the store method with a given name and query value I get the error: SQLSTATE[42S22]: Column not found: 1054 Unknown column '_token' in 'field list'.

It's obvious a _token field gets send with the request but I'm a bit baffled why it's trying to store it with the actual SQL query as it's not listed in the $fillable array.

Why is it getting mass assigned?


Solution

  • You use Query Builder's method insert. It doesn't check the fillable.
    You should use the create or update method of Eloquent.
    Please, read the documentation.

    Also, you may pass input data to construct or fill method of Eloquent. After that you may use the save method.