How to echo object name of an array in Laravel controller

Viewed 461

how do I display an object name of an array that I fetched from the database in Laravel blade? When I dump array in Laravel controller I get this "name" => "{"name":"Item 1"}". Now, how do extract Item 1 from array and display in a blade while looping using foreach.

Controller

$data = DB::table('items')
            ->select('name')
            ->where('id', $user->id)
            ->get();
   $output = json_decode($data,true);
   dd($output);


Results

"name" => "{"name":"Item 1"}

Kindly help.

2 Answers

You have to extract from each object separately.

Variant 1:

Controller:

$data = DB::table('items')->select('name')->where('id', $user->id)->get()
  ->map(function($item){
    $item->name = json_decode($item->name, true);
    return $item;
  });

return view('some_view', ['data' => $data]);

View:

@foreach($data as $d)
  <p>{{ is_array($d->name) ? $d->name['name'] : 'No Name' }}</p> {{-- Just Checking if Json is correctly decoded --}}
@endforeach

Variant 2:

Controller:

$data = DB::table('items')->select('name')->where('id', $user->id)->get();

View:

@foreach($data as $d)
  @php($name = json_decode($d->name, true))
  <p>{{ is_array($name) ? $name['name'] : 'No Name' }}</p>  {{-- Just Checking if Json is correctly decoded --}}
@endforeach

Controller:

$dataes = DB::table('items')
            ->select('name')
            ->where('id', $user->id)
            ->get();

return view('viewName',compact('dataes'));

View:

@foreach($dataes as $data)

{{ $data->name }}

@endforeach
Related