Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference an object property with a variable

I need to reference an object property with a variable like this:

$user = User::find( 1 );
$mobile = $user->getData( 'phone.mobile' );

The value of the $data property in the object is a jSON array. Right now my user class looks like this:

class User extends Authenticable {

    protected $fillable = [
        'email',
        'password',
        'data',
        'token',
    ];

    protected $casts = [
        'data' => 'array',
    ];

    public function getData( $key = null ){
        if( $key == null ){
            // Return the entire data array if no key given
            return $this->data;
        }
        else{
            $arr_string = 'data';
            $arr_key = explode( '.', $key );
            foreach( $arr_key as $i => $index ){
                $arr_string = $arr_string . "['" . $index . "']";
            }
            if( isset( $this->$arr_string ) ){
                return $this->$arr_string;
            }
        }
        return '';
    }
}

The code above, always returns '', but $this->data['phone']['mobile'] returns the actual value stored in the database. I guess I am referencing the key in a wrong way, can someone point me to the right way to access the value, given the string 'phone.mobile'

like image 334
Tales Avatar asked Feb 02 '26 08:02

Tales


1 Answers

Laravel actually has a built-in helper function for the exact thing you're trying to do called array_get:

  public function getData( $key = null ) 
  {
        if ($key === null) {
            return $this->data;
        }
        return array_get($this->data, $key);
  }

See documentation for more information: https://laravel.com/docs/5.5/helpers#method-array-get

like image 135
E. Schalks Avatar answered Feb 03 '26 22:02

E. Schalks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!