Ad

Laravel 5.1 QueryScope Or Accessor On Image With Path

- 1 answer

I am currently stuck on something. Right now I have an Ad controller that hasMany images.

class Ad extends Model
{
   public function images()
   {
       return $this->hasMany('Core\Entities\Ad\AdImages', 'ad_id', 'id')->orderBy('img_is_default', 'desc');
   }
}

The images table has a column for image_name (e.g my.jpg and another column for image path img_path (e.g 'custom/folder/images/date')

The problem or hassle here is when I loop out images in a view I have to also add in $result->image_path ./.$result->image_name.

Does anyone know how I can just get image path and image name combined into one from like a queryScope?

Basically I would just want to do like $result->primaryImage() which would then output custom/folder/images/date/myimage.jpg

^ already formatted.

Is this possible?

Ad

Answer

You could use an accessor

class AdImage ....
{
    public function getFullPathAttribute()
    {
        return $this->attributes['image_path'] .'/'. $this->attributes['image_name'];
    }
}

$img->full_path; // the combined value from above

Laravel 5.2 Docs - Eloquent - Accessors and Mutators

Ad
source: stackoverflow.com
Ad