panoply panoply - 2 months ago 21
JSON Question

Looping through mysql json data

Working with Laravel 5.3 and MySql 5.7 using

json
column type. I am not able to loop through the saved Json in my view. Here is how my setup looks:

Saved JSON in
"Merchants"
column:

["stores", "website"]


Retrieving this JSON with Eloquent:

$navigation = Merchant::select('merchants')
->where('user_id', Auth::user()->id)
->get();

return View::make('dashboard', compact('navigation'));


Lastly my View:

@foreach($navigation as $key => $value)
<li><a href="#">{{$value->merchants}}</a></li>
@endforeach


The results don't loop through the saved
JSON
instead it just displays the actual JSON saved, eg:
["stores", "website"]
however I want to loop this so it would list each value from the json array, eg:

<li>stores</li>
<li>website</li>


Thanks.

See my attached dump:

dump

Answer

You need to cast it in the model.

protected $casts = [
    'merchants' => 'json'
];

EDIT

You may need to change in your blade

@foreach($navigation as $value)
  @foreach($value->merchants as $merchant)
    <li><a href="#">{{$merchant}}</a></li>
  @endforeach
@endforeach