Laravel — How To Get String Value From Object Via Model Method?

- 1 answer

I have model House with relation hasMany HousePhotos. I try get link to main photo from table house_photos.

class House extends Model

    public function photos(){

    return $this->hasMany('app\HousePhoto');


    public function get_main_photo(){

    return $this->photos()->where('main', true);





In View i use


and got error.

When i use


i got object. How to get string value of link to photo?



First of all you need to understand the difference between the Builder object and the Collection object.

As it is now, function get_main_photo returns a Builder object (actually a Relation object, which contains a Builder).

On these objects you can call function get() to finish the query and get the results. In this case you will get a Collection object, which you will be able to iterate. Alternatively, in this case you seem to only have one 'main photo' per house, so instead you can call first():

public function get_main_photo(){    
    return $this->photos()->where('main', true)->first();    

This will return the single associated model, on which you will be able to access ->link (if the model was found).

Remember at any point while debugging you can call the convenient dd function (which dumps the object passed as parameter and terminates the applicacion) to see what type of object you are dealing with, and all its attributes.