Nazar Abubaker
Nazar Abubaker

Reputation: 505

Getting JSON fiile into Laravel

I'm trying to get my JSON file to go through a loop on test.blade.php

So far, if I print_r in jsonController.php then I can see the decoded JSON file but it'll be at the top of test.blade.php which is not what I want it to do.

I'm sure I'm missing something very obvious but I'm pulling blanks.

jsonController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class jsonController extends Controller
{
    public function press_kit() {
        $jsonString = file_get_contents(base_path('resources/views/inc/press-kit.json'));
        $json = json_decode($jsonString, true);

        return view('press-kit', $json);
    }
}

routes/web.php

Route::get('press-kit', 'jsonController@press_kit', function () {
    return view('press-kit');
});

test.blade.php

@for($x = 0; $x < count($json['articles']); $x++)
<div class="col-md-4 col-sm-6 col-12">
    <div class="card mb-sm-5 mb-3">
    <a href="{{ $json['articles'][$x]['url'] }}" target="_blank">
            <div class="w-100" style="background-image:url('img/{{ $json['articles'][$x]['thumbnail'] }} ');"></div>
            <div class="card-body">
                <h5 class="card-title">{{ $json['articles'][$x]['name'] }}</h5>
                <small>{{ $json['articles'][$x]['datePosted'] }}</small>   
            </div>
    </a>
        </div>
</div>
@endfor

Upvotes: 0

Views: 72

Answers (2)

rchatburn
rchatburn

Reputation: 752

Remove return view('press-kit');

Route::get('press-kit', 'jsonController@press_kit');

Your controller can just return the view

and change return view('press-kit', $json); to return view('press-kit', [ 'json' => $json]);

And you can access it with $json. Also just do an a for each instead of a for loop

@foreach ($json['articles'] as $article)
    {{$article['url'}}
@endforech

Much cleaner code in the long run.

Upvotes: 2

Piazzi
Piazzi

Reputation: 2636

Modify your route:

Route::get('press-kit', 'jsonController@press_kit');

And in your controller do this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class jsonController extends Controller
{
    public function press_kit() {
        $jsonString = file_get_contents(base_path('resources/views/inc/press-kit.json'));
        $json = json_decode($jsonString, true);

        return view('press-kit', compact('json'));
    }
}

Upvotes: 0

Related Questions