Laravel array shows as null before data array

1921 views laravel
5

I have a user that has many properties. This is user should also be able tp view the offers bet on his properties.

So have the relationship set.

User.php

public function properties(){
    return $this->hasMany('App\Property');
}

Property.php

public function offers(){
    return $this->hasMany('App\Offer');
}

Then in my controller this is what I have:

public function my_offers(){

    $properties = Property::whereUserId(Auth::id())->get();


    return view('pages.seller.offers.index', compact('properties'));
}

Then I go to my views like this:

@if($properties)
<ul>
    @foreach($properties as $property)

        <li>{{$property->offers->offer_message}}</li>

    @endforeach
</ul>
@endif 

When I view the page I see the below error:

Property [offer_message] does not exist on this collection instance.

But this property exists in my table.

If I change my list item to the one below I can see the array:

 <li>{{$property->offers}}</li>

I also see that before and after the array with the data, there are two empty arrays as the image shows below:

enter image description here

Is there anything that I didn't correctly?

Hope someone can help

answered question

Well, it seems that not all the properties have offers. Is that something you would expect?

No, not all properties have offer.

1 Answer

0

If not all the properties have offers, then you should check that before the <li>, besides that, offers is a collection, you need to loop through it, that's why you get the error.

@if($properties)
<ul>
    @foreach($properties as $property)
        @if ($property->offers)
            @foreach ($property->offers as $offer)
                <li>{{$offer->offer_message}}</li>
            @endforeach
        @endif
    @endforeach
</ul>
@endif

If you want to get only de properties that have offers (Querying Relationship Existence):

$properties = Property::whereUserId(Auth::id())->has('offers')->get();

And you should probably eager load that relationship:

$properties = Property::whereUserId(Auth::id())->has('offers')->with('offers')->get();

posted this

Have an answer?

JD

Please login first before posting an answer.