Laravel Dynamic Fillable in Models

Create a trait that uses the database columns.

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Schema;

trait ColumnFillable
{
    public function getFillable()
    {
        return Schema::getColumnListing($this->getTable());
    }
}

Now use this trait in your models.

<?php

namespace App;

use App\Traits\ColumnFillable;

class MyModel extends Model
{
    use ColumnFillable;

    ...

Now you'll never have to manually specify $fillable.


Try this. Put the below code in your model,

public function __construct()
{
    $this->setFillable();
}
public function setFillable()
{
    $fields = \Schema::getColumnListing('table_name_here');

    $this->fillable[] = $fields;
}

This makes each and every column is fillable from that table.


What you are really trying to do is make ALL fields fillable.

The correct way to do this in Laravel is this:

protected $guarded = [];

This works in 5.2, even though the documentation for it is found in 5.3.

(relevant source code for 5.2)

(Documentation from 5.3):

If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array:

By setting $guarded to an empty array, you are creating an empty black list, allowing all fields to be mass assignable.

Also, if this model is ever going to be constructed directly from user input, please do not do this. Laravel requires either $fillable or $guarded to be defined for a reason. Unless your model has fields that are literally 1:1 with a public form, then allowing all fields to be writable on mass assignment is a security vulnerability.