1

I'm trying to add an attribute to my model so I can say something like: $model->path and then get back a url. So I've added the following to the model's constructor:

public function __construct($attributes = array()){

    $this->path = url('img/' . $this->{'file-name'});
    parent::__construct($attributes);

}

But if I run Model::first() then I get the following:

{
  id: 25,
  text: "A lovely file",
  file-name: "file.jpg",
  created_at: "2016-02-12 11:44:37",
  updated_at: "2016-02-12 11:44:37"
},

You'll notice that there is no path attribute. Am I doing something very wrong?! I want to see:

{
  id: 25,
  text: "A lovely file",
  file-name: "file.jpg",
  path: "http://myapp.app:8000/img/file.jpg",
  created_at: "2016-02-12 11:44:37",
  updated_at: "2016-02-12 11:44:37"
},

For the record, I have also tried $this->field = 'value'; and that didn't create an attribute either.

1 Answer 1

5

Read the documentation. You’d be better off using an accessor method.

public function getPathAttribute()
{
    return url('img/'.$this->file_name);
}

You also shouldn’t be using dashes in column/property names, use the convention of underscores for separators.

Sign up to request clarification or add additional context in comments.

3 Comments

You'll also need the $appends property if the path attribute doesn't exist on the model or table. Hidden at: laravel.com/docs/5.1/…
That's great, thanks – and noted on the hyphen. Is there any way of including this attribute automatically, or am I best off doing something like: $imgs = \App\Img::all(); foreach($imgs as $img){ $img->url = $img->path; – just so the collection I return for my API is formatted nicely?
@Djave As @Mysteryos says, you can add path to your $appends array and that’ll include the value in any serializing to JSON, arrays etc.

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.