kukri
kukri

Reputation: 93

Pass json data to blade view from controller

I am loading a json file from my resources folder resources/data/example.json

public function __construct()
{
    // Load json file 
    $path = base_path('resources/data/rooms.json');
    $content = file_get_contents($path);
    $data = json_decode($content);
}

my json file looks like this, it's a simple one just for an example:[ { "id":"bicycle", "category":"vehicle", "name":"Bicycle One", "images":[ "/img/bike_slider_1.jpg", "/img/bike_slider_2.jpg" ], },

so now I am wondering how can I pass some of this data to the view which is e.g bikes.blade.php which looks like this: @extends('layouts.default') @section('content') <main>{{ content[1] }}</main>

any help will be appreciated :)

Upvotes: 0

Views: 1580

Answers (2)

Piash
Piash

Reputation: 1131

https://laravel.com/docs/8.x/views#passing-data-to-views

you can follow this link. You already convert JSON data into object. Now just pass it from controller.

return view('yourBladeFile')->with('data ', $data );

Now in blade file you can read it like:

@foreach($data as $item)
  <p> {{$item->name}} </p>
@endforeach

or other suitable way for you.

Upvotes: 2

Alex Black
Alex Black

Reputation: 462

    public function index()
    {
        // Load json file 
        $path = base_path('resources/data/rooms.json');
        $content = file_get_contents($path);
        $data = json_decode($content);
    
        return view('bikes', [
                'items' => $data,
            ]);
    }

Inside blade

@foreach ($items as $item) 
    {{ $item->name }}
@endforeach

Upvotes: 3

Related Questions