Furkan ozturk
Furkan ozturk

Reputation: 722

Why does it gives an error as undefined property in my model?

In my model the First method works fine but if second method is written it gives error as undefined property for is_finished property

//Model
protected $fillable = ['is_finished'];
protected $appends = [ 'is_recorded' ];

public function getIsRecordedAttribute()
{
    if($this->is_finished > 1){ // it can be 2,3
        return 1;
    }
    return 0;
}

//the below getIsFinishedAttribute() method gives an error message 
//that is Undefined property: App\Models\Backend\MeetingContent::$is_finished in file
public function getIsFinishedAttribute()
{
    if($this->is_finished > 0){
        return 1;
    }
    return 0;
}

How can i fix my model? I don't want to show the is_finished property as it is because it can be higher than 1

Upvotes: 1

Views: 1867

Answers (1)

Frnak
Frnak

Reputation: 6812

Based on the laravel docs https://laravel.com/docs/7.x/eloquent-serialization you should access the attribute in a different way

public function getIsAdminAttribute()
{
    return $this->attributes['admin'] === 'yes';
}

so for your example

public function getIsRecordedAttribute()
{
    if($this->attributes['is_finished'] > 1){
        return 1;
    }
    return 0;
}


public function getIsFinishedAttribute()
{
    if($this->attributes['is_finished'] > 0){
        return 1;
    }
    return 0;
}

Upvotes: 2

Related Questions