$cityAds
, when you use ->get()
is a Collection of multiple Ad
instances, and your code doesn't know how to handle [Ad, Ad, Ad]->categories
. You need to use ->first()
(like in your working example), or loop over $ads
:
$cityAds = Ad::where('city_slug', $sCity)->first();
$city = $cityAds->categories;
dd($city);
// OR
$cityAds = Ad::where('city_slug', $sCity)->get();
foreach($cityAds as $cityAd) {
$city = $cityAd->categories; // Do something with `$city` in this loop
}
As a side note, categories()
is also returning a Collection
, so $city
as the variable name doesn't make a lot of sense. Consider the following:
$cityAds = Ad::with('categories')->where('city_slug', $sCity)->get();
foreach($cityAds as $cityAd) {
foreach ($cityAd->categories as $category) {
// Do something with `$category` in this nested loop
}
}
Or, lastly, adjust your relationship to a hasOne()
, if you're only expecting a single Category
model, then do $cityAd->category
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…