Erhnam
Erhnam

Reputation: 921

Laravel create dynamic attribute when doing write in Model

I wonder if it is possible to create or set an attribute when writing in the Model. I tried to do it with a setMutator, but when the attribute is not provided in the list with arguments for a save the value is not created

public function setExampleAttribute($value)
{
    $this->attributes['example'] = 100;
}

So when I do this:

Version::create(['name' => 'mark', 'example' => '50');

The record is saved with 100.

But when I do this:

Version::create(['name' => 'mark');

The record is empty.

Is there a way to do something in between? So before the object is written, add some dynamic content?

Upvotes: 1

Views: 4806

Answers (3)

Neo
Neo

Reputation: 11587

In your Version Model:

class Version extends Model {
 public function __construct() {
        if(!isset($this->example))$this->example=100;  
    }
}

Upvotes: 0

Peter Pointer
Peter Pointer

Reputation: 4170

Override fill()

Consider moving this to a base class or a trait, it's just an example:

<?php
class Version extends Model {

  public function fill(array $attributes) {
    parent::fill($attributes);

    // Your own implementation here
  }
}

See: Eloquent Model::fill() source for 5.8

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

It doesn't work, because create() uses fill() to set attribute values. You can try to use $attributes to set default value:

protected $attributes = ['example' => 100];

If you want to add a dynamic attribute, you can use Eloquent creating event inside of which set attribute:

$this->attributes['example'] = $value;

Or call mutator:

$this->setExampleAttribute(null);

Upvotes: 1

Related Questions