micky
micky

Reputation: 317

Accessing the values from relation laravel

$show=Product::where(['product_id'=>$id])->first();         
 if($show)
  {
     echo json_encode(array('status' => TRUE,  'show'=>$show); die;
  } 

product has relation 'category' with category table and category table has column 'name'. I am trying to access that name this way but failed.there is no problem with price though.

ajax and javascripts:

$.ajax({
        type: "POST",
        url: "{{url('/product/show')}}",
        data: {id:id},
        success: function (data) {
        var res = $.parseJSON(data);

        if(res.status == true)
        {                        
             var result ='Price:' +res.show.price+'<br>'+
                         'Category:'+res.show.category.name'<br>'+  
        }

Upvotes: 1

Views: 55

Answers (1)

Mina Abadir
Mina Abadir

Reputation: 2981

You need to ensure that the relationships are loaded from your SQL, and returned with your variable.

$show=Product::where(['product_id'=>$id])->with('category')->first();         

Upvotes: 1

Related Questions