PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, January 28, 2022

[FIXED] Laravel - Update another attribute when updating model

 January 28, 2022     eloquent, laravel, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing