Home » Php » Accessing Laravel relations in JavaScript code

Accessing Laravel relations in JavaScript code

Posted by: admin October 29, 2017 Leave a comment

Questions:

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
}
Answers:

Why declare all these variables:

$category = $show->category->category;
$username = $show->user->username;
$getbrands = $show->productbrand;

If category, user, productbrand and then brands are models relation with product and to fetch category from category, username from user, etc.

Instead maintain the relations with ‘with’;

public function show(Request $request)
{
    if($request->ajax())
    {
       $id = $request->id;
       if($id)
       {
           $show = Product::where(['product_id'=>$id])->with('category')
                                                      ->with('user')
                                                      ->with('productbrand.brand')  // product has onetomany relation 'productbrand' with table productbrand and productbrand has onetoone relation 'brand' with table brand
                                                      ->first();
           if($show)
           {
               echo json_encode(array('status' => TRUE,  'show'=>$show)); die;
           }
       }
    }
  echo json_encode(FALSE);die;

And in JavaScript:

        if(res.status == true)
        {
            var result = 'Category: ' + res.show.category.category + '<br>' +
                         'Product by: ' + res.show.user.username + '<br>' +
                         'Price: ' + res.show.price + '<br>' +
                         'Price type: ' + res.show.price_type + '<br>' +
                         'Product Views: ' + res.show.views + '<br>';
            $('#result').html(result);
        }
    }
});

product has onetomany relation ‘productbrand’ with table productbrand and productbrand has onetoone relation ‘brand’ with table brand. table brand has a column ‘brand’. And am not not being able to access the brand of the product. Access brand like this.

var result = 'Brands: ';
for(var i=0; i<res.show.productbrand.length; i++)
{
    result += res.show.productbrand[i].brand.brand;
}

Questions:
Answers:

Using your first way.

Change $brand=$getbrand->brand->brand; to $brand[] = $getbrand->brand->brand;

And then in js you can go over the brands like this:

for(var i=0; i < res.brand.length; i++)
{
    console.log(brand[i]);
}

However getting brands like this will do a lot of database query.

Instead, you can use eager loading.

Like this:

$show = Product::with('productbrand.brand')->where(['product_id'=>$id])->first();
$brand = $show->productbrand->pluck('brand')->collapse();

And access it the same way in js as before.

PS: I am assuming you are using laravel 5.2.

Questions:
Answers:

I think you should create a route and use AJAX to get the data you need.
Once you pass the data to the DOM that javascript uses it does not have any knowledge about the object relations you defined in Laravel.

Leave a Reply

Your email address will not be published. Required fields are marked *