TheRealPapa TheRealPapa - 6 months ago 13
PHP Question

MySQL column contains PHP array content, loop

I am working with Laravel 5.2. I have a text (string) column in a MySQL table that contains a PHP array for breadcrumbs like this.

['employee.index' => 'Employees']


On suggestion by @weigreen I tried also JSON format for the string content like this:

{'employee.index': 'Employees'}


I then want to loop through it in my
blade
template like this:

@if($pageBreadcrumbs)
@foreach($pageBreadcrumbs as $route => $name)
@if ($name == end($pageBreadcrumbs))
<li class="active">{!! $name !!}</li>
@else
<li><a href="{!! route($route) !!}">{!! $name !!}</a></li>
@endif
@endforeach
@endif


But I have not been able to successfully get PHP to interpret the contents of this field as an array.

I have tried various combinations of this code:

$breadcrumbsArray = array();
$breadcrumbsArray = $page->breadcrumbs;
View::share('pageBreadcrumbs', $breadcrumbsArray);


and

$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);


Any help is appreciated.

Answer

Try to convert back to php object and use it.

If you doesn't convert it your data will be seen as string by php.

$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);