Reputation: 53
ProductDetail Model:
public function getProduct(){
return $this->belongsTo('App\Models\Products');
}
Product model:
public function detail(){
return $this->hasOne('App\Models\ProductDetails');
}
homepage blade:
@foreach ($product_slider as $index=>$product_details)
<div class="ps-banner"><img class="mobile-only" src="{{asset('farmart/')}}/img/slider/home-1/slide_03_mobile.png" alt="alt"><img class="desktop-only" src="{{asset('farmart/')}}/img/slider/home-1/slide_03.png" alt="alt">
<div class="ps-content {{ $index==0 ? 'active':'' }}">
<div class="container">
<div class="ps-content-box">
<div class="ps-node"><span class='text-danger'>SALE UP TO 30%</span></div>
<div class="ps-title">{{ $product_details->getProduct->product_name}}</div>
<div class="ps-subtitle">Only from <br><span class='price'>{{ $product_details->getProduct->price }} TL</span></div>
<div class="ps-shopnow"> <a href="shop-view-grid.html">Shop Now<i class="icon-chevron-right"></i></a></div>
</div>
</div>
</div>
</div>
@endforeach
HomeController :
$product_slider=ProductDetails::with('getProduct')->where('show_slider', 1)->take(3)->get();
return view('homepage' ,compact('product_slider'));
error-->Trying to get property 'product_name' of non-object
Upvotes: 0
Views: 159
Reputation: 12401
your getting this error because in $product_details->getProduct->product_name
here getProduct
is undefined
so it will be $product_details->undefined->product_name
so here you cannot get product_name
of undefined
you can skip the $product_slider
which doesnot have $product_details
@foreach ($product_slider as $index=>$product_details)
@if (!$product_details->getProduct)
@continue
@endif
<div class="ps-banner"><img class="mobile-only" src="{{asset('farmart/')}}/img/slider/home-1/slide_03_mobile.png" alt="alt"><img class="desktop-only" src="{{asset('farmart/')}}/img/slider/home-1/slide_03.png" alt="alt">
<div class="ps-content {{ $index==0 ? 'active':'' }}">
<div class="container">
<div class="ps-content-box">
<div class="ps-node"><span class='text-danger'>SALE UP TO 30%</span></div>
<div class="ps-title">{{ $product_details->getProduct->product_name}}</div>
<div class="ps-subtitle">Only from <br><span class='price'>{{ $product_details->getProduct->price }} TL</span></div>
<div class="ps-shopnow"> <a href="shop-view-grid.html">Shop Now<i class="icon-chevron-right"></i></a></div>
</div>
</div>
</div>
</div>
@endforeach
ref link https://laravel.com/docs/8.x/blade#loops
incontroller only retrun those which have products
$product_slider=ProductDetails::has('getProduct')->with('getProduct')->where('show_slider', 1)->take(3)->get();
return view('homepage' ,compact('product_slider'));
ref link https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Upvotes: 0
Reputation: 79
productDetails model:
public function getProduct(){
return $this->belongsTo('App\Models\Products','products_id');
}
fix as above
Upvotes: 1