-
Notifications
You must be signed in to change notification settings - Fork 1
Property Hooks
macropay-solutions edited this page Oct 13, 2025
·
2 revisions
Read more about Active record segregation properties
ModelAttributes class look like this in PHP < 8.4:
<?php
namespace App\Models\Attributes;
use MacropaySolutions\LaravelCrudWizard\Models\Attributes\BaseModelAttributes;
/**
* @property string $first_name
* @property string $last_name
* ...
*/
class UserAttributes extends BaseModelAttributes
{
}Starting with PHP 8.4 it can look like this:
<?php
namespace App\Models\Attributes;
use MacropaySolutions\LaravelCrudWizard\Models\Attributes\BaseModelAttributes;
class UserAttributes extends BaseModelAttributes
{
public string $full_name {
get => $this->last_name . ' ' . $this->first_name;
set(string $value) {
$this->ownerBaseModel->setAttribute('full_name', $value); // if you want it to be persisted in the model
}
}
//optional; can remain as @property string $first_name
public string $first_name {
get => $this->ownerBaseModel->getAttributeValue('first_name');// or $this->__get('first_name');
set(string $value) {
$this->ownerBaseModel->setAttribute('first_name', $value);// or $this->__set('first_name', $value);
}
}
// optional; can remain as @property string $last_name
public string $last_name {
get => $this->ownerBaseModel->getAttributeValue('last_name');
set(string $value) {
$this->ownerBaseModel->setAttribute('last_name', $value);
}
}
}making it a true entity. That also means that clashes with the Model’s properties are history.
Note that property hooks don’t work well with arrays! Read more here.
Also to make sure these are used also for $model->full_name not only for $model->a->full_name, override in your model:
public function __set($key, $value)
{
$this->a->{$key} = $value;
}
public function __get($key)
{
return $this->hasAttribute($key)
? $this->a->{$key}
: $this->r->{$key};
}If getAttribute, getAttributeValue or setAttribute methods are used, the property hooks are not called both in model and in the above scenario.