Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

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?

0 likes
4 replies
Sinnbeck's avatar

It almost looks like it's double encoded. How are you saving it?

1 like
eggplantSword's avatar

@Sinnbeck $user->apps()->attach($this->app_id, ['roles' => json_encode($this->user_types)]); that's how I save it to the relationship

eggplantSword's avatar

@mabdullahsari @sinnbeck Yes it was, I ended up changing the select in the blade view to "regular" where <option value="{{ $type }}">{{ $type['label'] }}</option> and in the method I create the array and save it, that way it only gets encoded once.

Please or to participate in this conversation.