Encountering the error message Undefined variable: $productsTR
, even though I have initialized the products variable in the controller. My setup includes a main blade and a partial blade, where the main blade sends data to the controller before it is returned to the partial blade. How can I address the issue of Undefined variable: $productsTR
?
HomeController
public function viewProduct($id){
$productsTR = Product::with('ProductsPhoto')->where('id',$id)->get();
$returnHTML = view('productdetail')->with('productsTR', $productsTR)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
Route
Route::get('view-product/{id}', 'HomeController@viewProduct')->name('view.producT');
Partial Blade(productdetail)
@foreach($productsTR as $product)
@foreach($product->ProductsPhoto as $productImage)
<img src="{{ Storage::url($productImage->filename) }}" alt="small">
@endforeach
@endforeach
Main blade
<div class="modal fade" id="view-product" tabindex="-1" role="dialog" aria-
labelledby="myModalLabel">
<div class="modal-dialog" role="document">
@include('productdetail')
</div>
</div>
@foreach($products as $product)
@if(count($product->ProductsPhoto))
<a href="javascript:;" id="{{$product->id}}" class="modal-global" >
<img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt="" >
</a>
@endif
@endforeach
Javascript
<script>
$('.modal-global').click(function(event) {
event.preventDefault();
var product_id = $(this).attr("id");
var url = '{{route('view.producT',[":product_id"])}}';
url = url.replace(':product_id', product_id);
$("#view-product").modal('show');
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
})
.done(function(response) {
$("#view-product").find('.view-product').html(response);
});
});
</script>
Main blade (ProductController)
public function index(Request $request)
{
$userId = $request->user()->id;
$products = product::where('user_id', $userId)->paginate(20);
return view('product.index',compact('products'));
}
Main blade Route
Route::get('/user/product', 'ProductController@index');