Product has a one-to-many relation, 'productbrand', with table productbrand and productbrand has a one-to-one relation, 'brand', with table brand. Table brand has a column, 'brand'. And I am able to access the brand of the product. All other categories, username, etc. are accessed properly.
public function show(Request $request)
{
if($request->ajax())
{
$id = $request->id;
if($id)
{
$show = Product::where(['product_id'=>$id])->first();
$category = $show->category->category;
$username = $show->user->username;
$getbrands = $show->productbrand;
foreach($getbrands as $getbrand)
{
$brand=$getbrand->brand->brand;
}
if($show)
{
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'brand' => $brand)); die;
}
}
}
echo json_encode(FALSE);die;
}
Ajax and jQuery:
$.ajax({
type: "POST",
url: "{{url('/product/show')}}",
data: {id:id},
success: function (data) {
var res = $.parseJSON(data);
if(res.status == true)
{
var result = 'Category: ' + res.category + '<br>' +
'Product by: ' + res.username + '<br>' +
'Brands: ' + res.brand + '<br>' +
'Price: ' + res.show.price + '<br>' +
'Price type: ' + res.show.price_type + '<br>' +
'Product Views: ' + res.show.views + '<br>';
$('#result').html(result);
}
}
});
This way I could get only one brand. I have also tried the following way, but failed.
In the controller:
$getbrands = $show->productbrand;
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'getbrands' => $getbrands));
In Ajax:
for(var i=0; i<res.getbrands.length; i++)
{
var brands=res.getbrands[i].brand.brand; //First 'brand' is relation and second is the brand I am trying to access
}