In laravel 11 / livewire 3 / app I added shouldBeStrict to model :
class Currency extends Model implements HasMedia {
protected $table = 'currencies';
protected $primaryKey = 'id';
public $timestamps = false;
protected static function boot()
{
parent::boot();
if(App::isLocal()) {
Model::shouldBeStrict();
}
}
So now I can not use code like :
$currency->selected = true;
So I add 2 custom attributes in model :
protected $appends = ['select', 'mediaData'];
...
// Set select value.
public function setSelectAttribute(bool $value): void
{
$this->attributes['select'] = $value;
}
// Get select value.
function getSelectAttribute()
{
return $this->attributes['select']; // ERROR POINTING TO THIS LINE
}
// Set mediaData value.
public function setMediaDataAttribute(array $value): void
{
$this->attributes['mediaData'] = $value;
}
// Get mediaData value.
function getMediaDataAttribute(): array
{
return $this->attributes['mediaData'];
}
But with first request to this model :
foreach ($this->currencies as $currency) {
var_dump($currency->select);
}
I got error :
Undefined array key "select"
How to fix it ?
class Currency extends Model implements HasMedia
{
protected $table = 'currencies';
protected $primaryKey = 'id';
public $timestamps = false;
// Define custom attributes that should be appended to the model's JSON form
protected $appends = ['select', 'mediaData'];
// Internal variables to hold custom attribute values
protected $customAttributes = [
'select' => false, // Default value for `select`
'mediaData' => [], // Default value for `mediaData`
];
// Override the boot method for strict mode if in local environment
protected static function boot()
{
parent::boot();
if (App::isLocal()) {
Model::shouldBeStrict();
}
}
public function setSelectAttribute(bool $value): void
{
$this->customAttributes['select'] = $value;
}
public function getSelectAttribute()
{
return $this->customAttributes['select'] ?? false;
}
public function setMediaDataAttribute(array $value): void
{
$this->customAttributes['mediaData'] = $value;
}
// Get mediaData value (retrieve it from the custom attributes array)
public function getMediaDataAttribute(): array
{
return $this->customAttributes['mediaData'] ?? [];
}
}
Try this