Home > OS >  How to use not static attributes as default values in Eloquent?
How to use not static attributes as default values in Eloquent?

Time:03-15

There's classes and schedules. Strictly, one SchoolClass to one Schedule. The creation of a Schedule depends on a SchoolClass, so I decided to inject SchoolClass on constructor to constrain the association.

class Schedule extends Model
{
    // ...

    private $class;

    public function __construct(SchoolClass $class)
    {
        $this->class = $class;
    }

    // Used to limit domain, based on the associated class_id
    protected static function booted()
    {
        static::addGlobalScope('class', function (Builder $builder) {
            $builder->where('class_id', $this->class->id);
        });
    }

    public function getClassIdAttribute()
    {
        return $this->class->id;
    }
    
    // ...
}

By this way, I can obtain the class_id associated with the Schedule

new Schedule(SchoolClass::find(1))->class_id; // Returns 1, as supposed 

When creating a Schedule, associated to a SchoolClass, I want that builder consider the class_id attribute, but when I try to save it:

new Schedule(SchoolClass::find(1))->save(); // General error: 1364 Field 'class_id' doesn't have a default value

CodePudding user response:

You've probably not set class_id in the fillable array. If you do that or make an empty guarded array, the error should be resolved.

CodePudding user response:

I found a possible solution.

Updating model $attributes on the constructor:

public function __construct(SchoolClass $class)
{
    $this->class = $class;
    $this->attributes['class_id'] = $class->id;
}

So, until now the model wasn't fullfiled with class_id, and wasn't considering that field on save() method.

By the way, I believe there will be a better solution.

  • Related