J. Doe
J. Doe

Reputation: 999

Automatically set attributes using Laravel Eloquent

I have some attributes, that I need to set automatically when using create() or save() methods.

Model:

class SampleModel extends Model
{
    protected $guarded = ['id'];

    public function setRandomColumnAttribute($value=null)
    {
        if(!is_string($hostname)){
            $value = "I set the value here";
        }

        $this->attributes['random_column'] = $value;
    }
}

Controller

use App\SampleModel;

class SomeController extends Controller
{
    public function something()
    {
        SampleModel::create([
            'name' => 'Jeff',
        ]);

        // or instead of the above:
        // $model = new SampleModel;
        // $model->name = 'Jeff';
        // $model->save();
    }
}

I need to save random_column value, that is defined in the Model itself as you see, without passing it from the controller.

Please note if I use:

    SampleModel::create([
        'name'          => 'Jeff',
        'random_column' => true // or anything other than string
    ]);

It works and set the value, but is there any way to avoid passing this every time and just set it automatically in the Model?

Upvotes: 0

Views: 4040

Answers (1)

Uzair Riaz
Uzair Riaz

Reputation: 919

Did you try observers? Add boot() method to your SampleModel:

protected static function boot()
{
    parent::boot();
    static::creating(function (SampleModel $model) {
        $model->random_column = 'Random column';
    });
}

Creating will trigger everytime a ->create() is called on a SampleModel.

Upvotes: 2

Related Questions