Issue
In one of my models I need to update another attribute when two other attributes from the same model are updated.
In my case, using an Accessor
is not an option, because in some cases I will need to do a database query looking for full_phone_number
.
What is the best to achive the desired result?
This is my model:
class Address extends Model {
protected $fillable = [
'country_code',
'phone_number',
'full_phone_number',
];
}
When I create a new Address
, I need the full_phone_number
column to be automatically populated:
$address = Address::create([
'country_code' => 55,
'phone_number' => 1199999999
]);
The expected result is:
# Address model on DB
{
"country_code": 55,
"phone_number": 1199999999,
"full_phone_number": 551199999999
}
When I update country_code
or phone_number
from an Address
, I need the full_phone_number
column to be automatically updated:
$address->update([
'phone_number' => 1188888888
]);
The expected result is:
# Address model on DB
{
"country_code": 55,
"phone_number": 1188888888,
"full_phone_number": 551188888888
}
Solution
I got the desired result using events
, but I don't know if this is the best way to handle this case. The same could be converted to an observer
.
class Address extends Model {
protected $fillable = [
'country_code',
'phone_number',
'full_phone_number',
];
protected static function boot()
{
parent::boot();
static::updating(function ($address) {
$address->full_phone_number = $address->country_code . $address->number;
});
}
}
Answered By - Caio Kawasaki
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.