Array Json Casting in Laravel Store Retireve Nested Data

Cast a field in the Model

protected  $casts  =  [
    'options'  =>  'array',
];

Now when you insert it into the DB, Laravel will take care you converting it to and back when you fetch the data.

Additionally

There could be another scenario when you would not want to cast it as an array. In such a case, the scenario could be handled as below:

$product  =  Product::select('options')->where('id',  $prodID)->first()->options;
return view('single-product',  [  'productDetails'  => collect(json_decode($product))  ]);

Display each key:value pair in the Blade. This will render each option which is a single element in the array.

@foreach ($productDetails->options  as  $opt)
    <div>{{  $opt  }}</div>
@endforeach
comments powered by Disqus