That's what json_decode does and yes.
Why
json_decode(json_encode($productDetails));
here's my controller
public function addAttributes(Request $request, $id=null)
{
$productDetails = Product::with('attributes')->where(['id' => $id])->first();
$productDetails = json_decode(json_encode($productDetails));
echo "<pre>"; print_r($productDetails); die;
}
it gives me this
stdClass Object
(
[id] => 3
[category_id] => 2
[product_name] => valenciaga
[product_code] => 4
[product_color] => black
[description] => quality shoes running shoes
[price] => 200
[image] => 87910.jpeg
[created_at] => 2019-02-20 11:51:18
[updated_at] => 2019-02-20 11:52:28
[attributes] => Array
(
[0] => stdClass Object
(
[id] => 1
[product_id] => 3
[sku] => rt-1
[size] => small
[price] => 200
[stock] => 5
[created_at] => 2019-02-20 16:16:51
[updated_at] => 2019-02-20 16:16:51
)
[1] => stdClass Object
(
[id] => 2
[product_id] => 3
[sku] => rt-2
[size] => medium
[price] => 300
[stock] => 10
[created_at] => 2019-02-20 16:16:51
[updated_at] => 2019-02-20 16:16:51
)
now here my view page
@foreach($productDetails['attributes'] as $attribute)
<tr class="gradeX">
<td>{{ $attribute->id }}</td>
<td>{{ $attribute->sku }}</td>
<td>{{ $attribute->size }}</td>
<td>{{ $attribute->price }}</td>
<td>{{ $attribute->stock }}</td>
<a rel="{{ $attribute->id }}" rel1="delete-product" href="javascript:" class="btn btn-danger btn-mini deleteRecord">Delete</a>
</tr>
@endforeach
now i got an error like this
2/2) ErrorException Trying to get property of non-object
should i use
<td>{{ $attribute['id'] }}</td>
to view my data?
public function addAttributes(Request $request, $id=null)
{
$productDetails = Product::with('attributes')->where(['id' => $id])->firstOrFail();
return view('admin.products.add_attributes', compact('productDetails'));
}
@foreach($productDetails->attributes as $attribute)
{{ $attribute->id }}
@endforeach
You also better be sure you get a result first. You're assuming you are but never check. For instance, if the $id doesn't exist you will get errors for trying to use a property on an object that doesn't exist. You should basically always use firstOrFail() instead of just first(). That way you will get an appropriate 404 page not found error instead if the $id didn't exist. https://laravel.com/docs/5.7/eloquent#retrieving-single-models
Please or to participate in this conversation.