0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, with $model->save() I was having this error: Maximum function nesting level of '256' reached, aborting! but now that you removed it, it works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.