I'm trying to get a selected product(id) from view to controller but it only shows the first product(id). So I have a loop of products which shows image of each product what I want is when a user select any image it should send the id according to the selected product. So far it only pick the first product id even if I click the last product(image) or any different image it only send the first product id. How can I fix this?
Blade
@foreach($products as $product)
@if(count($product->ProductsPhoto))
<a href="javascript:;" class="view-product" >
<img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt="" >
</a>
@else
@endif
@endforeach
Javascript
<?php $id = $product->id; ?>
<script>
$('.view-product').on("click", function(event) {
$("#view-product").modal('show');
$.ajax({
url: '{{route('view.producT', $id)}}',
type: 'GET',
dataType: 'json',
}).done(function(response) {
console.log('received this response: '+response);
});
});
</script>
Route
Route::get('view-product/{id}', 'HomeController@viewProduct')->name('view.producT');
Controller
public function viewProduct($id)
{
dd($id);
}
$(selector).attr().data-id="{{$product->id}}"in <a> tag then how do I fetch or where do I put the$(selector).attr()? @Tusharconst id = event.target.idand then can use it as you wish. We have to do event.target because we are listening to a click on .view-product class but we don't yet know which image was clicked. So this will take care of that part.