It almost looks like it's double encoded. How are you saving it?
Dec 13, 2021
4
Level 9
Display saved json from db in Blade. Cannot access offset of type string on string
I have a simple json I store in a varchar, the user selects the roles from a select
//how the user selects the roles (there are two selects: one multiple and one simple)
<x-forms.select class="w-full block mt-1" wire:model="user_types" multiple>
@foreach ($all_user_types as $type)
<option value="{{ json_encode($type) }}">{{ $type['label'] }}</option>
@endforeach
</x-forms.select>
//how I store it
$user->apps()->attach($this->app_id, ['roles' => json_encode($this->user_types)]);
//when I want to display it
@if ($app->pivot && $app->pivot->roles)
@foreach (json_decode($app->pivot->roles, true) as $role)
<span class="text-gray-400 text-sm font-semibold p-1">{{ $role }}</span>
@endforeach
@endif
This is the problem the data in the db looks like this
["{\"label\":\"Super Administrador\",\"value\":1}","{\"label\":\"Administrador\",\"value\":2}"]
So when I do @foreach (json_decode($app->pivot->roles, true) as $role) $role prints as a string
{"label":"Super Administrador","value":1}
{"label":"Administrador","value":2}
What I really need to display is the label only, however I'm not sure how to select that part only, I tried doing {{ $role['label'] }} and {{ $role->label }} but get errors
Cannot access offset of type string on string
Attempt to read property "label" on string
How can I display only the label?
Please or to participate in this conversation.