3

I have 3 different fields in the database: city, state, country. How do I define another attribute in Eloquent to return one string from those 3 fields?

First approach, but it doesn't work:

protected $address = "";

public function getAddress() : string {
  return $this->city . $this->state . " - " . $this->country;
}

2 Answers 2

10

If you want a new attribute which is not defined in model, you need to append that attribute to your model.

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = ['address'];

And define your attribute method:

/**
 * Get the address.
 *
 * @return string
 */
public function getAddressAttribute()
{
    return $this->city . $this->state . " - " . $this->country;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Add Attribute to the method name to make it work:

public function getAddressAttribute()
{
    return $this->city.$this->state.' - '.$this->country;
}

https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

1 Comment

That's for attributes already mapped to the database table, though. It returns nothing when I call $this->address

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.