user1441917 user1441917 - 3 months ago 12
JSON Question

JSON data and Laravel view

I've some JSON data stored in a field of my DB, to display the data in a view, I wrote this query in my controller

$gallerie = Articolo::select('nome_gal')
->where('nome_gal','LIKE','%nome_gal%')
->orderBy('created_at', 'desc')
->orderBy('updated_at', 'desc')
->take(6)
->get();


In the controller, I pass that query, and other queries, to a view in this way

return view('articoli')->with(array('articoli' => $articoli, 'gallerie'=>$gallerie, 'categorie'=> $categorie, 'trevideo'=>$trevideo, 'treaudio'=>$treaudio));


in the sidebar section of the view I used this code:

<div class="sidebar-item popular">
<h3>Ultime foto</h3>
<ul class="gallery">
@foreach(json_decode($gallerie, true) as $galleria)
<li>{{ $galleria['cover_gal'] }}</li>
@endforeach
</ul>
</div>


Well, as a result, when I try to load the page, I don't see any code under the
<ul class="gallery">
.

The structure of the JSON data is this http://p4c.it/alfa.json

Considering that
json_decode
needs a string, in my opinion there is something wrong in the controller part. Do you have any suggestion?

Answer

Well this is what i did and it worked for me, in the following, everything is recap, so the solution is complete for the new readers. In the model of the table I defined an imaginary attribute like so:

protected $appends=['att1','att2','att3', 'att4', 'nome_galla'];

and obviously

`public function getNomeGallaAttribute() {

$json = $this -> attributes['nome_gal'];

return json_decode($json, true);

}`

in the controller I've the query:

$gallerie = Articolo::select('nome_gal')->where('nome_gal','LIKE','%nome_gal%')->orderBy('created_at', 'desc')->orderBy('updated_at', 'desc')->take(6)->get();

and obviously the passage to the view:

return view('articoli')->with(array('articoli' => $articoli, 'gallerie'=>$gallerie, 'categorie'=> $categorie, 'trevideo'=>$trevideo, 'treaudio'=>$treaudio));

finally, in the view, I solved in this way:

<div class="sidebar-item popular"> <h3>Ultime foto</h3> <ul class="gallery"> @foreach($gallerie as $galleria) <li><a href="#"><img src="gallerie/{{$galleria['nome_galla']['nome_della_gal'] }}/img_rid/{{$galleria['nome_galla']['cover_gal'] }}" alt=""></a></li> @endforeach </ul> </div>

for some reason the regular syntax

{{asset("gallerie/$galleria['nome_galla']['nome_della_gal']/img_rid/$galleria['nome_galla']['cover_gal']")}}

didn't worked for me (white page of death as a result).

Thanks to everyone for the contribution, I know php but I'm new to laravel :-)

Comments