Send data to sidebar.blade.php only

Asked

Viewed 501 times

1

I need to build a menu using the registered categories. How can I do this without using a view?

I have my layout.blade.php with a @include('sidebar')
My consultation works on view categorias.blade.php, I just need to receive the data of the query in my sidebar.blade.php

Categoriacontroller:

public function listar() {
    $categorias = Categoria::where('categoria_id', '0')->with('todasCategorias')->get();
    return view('categorias', compact('categorias'));
}

I made the direct consultation on sidebar.blade.php.
It worked, but I think this is not the right way, someone knows another way?

$categorias = App\Categoria::where('categoria_id', '0')->with('todasCategorias')->get()

2 answers

1

See the code below.

On the line of return use with, to say that you will load the page with the list of categories. You do withCategorias. Categories is the name you will use on foreach in Blade. And the variable inside is the variable that makes the query, $categorias.

public function listar() {
    $categorias = Categoria::where('categoria_id', '0')->get();
    return view('categorias')->withCategorias($categorias);
}

Then in the Blade you do:

@foreach($categorias as $item)
   $item->nome_do_campo
@endforeach

You can use the function __construct()

public function __construct(){
   $categorias = Categoria::where('categoria_id', '0')->get();
   view()->share('categorias', $categorias);
}

Then apply the same concept above the foreach in sidebar.blade.php.

  • Diego, thank you for the answer. I don’t think I was very clear. Actually this sidebar.blade.php is not in the category.blade.php. The sidebar will be on every page of the site. I import the sidebar in my layout.blade.php

  • Knows how to use the function __construct ?

  • Yes, but it doesn’t work that way. Remembering that the view categorias has nothing to do with the sidebar. In fact where has categorias nor has the sidebar.

  • The sidebar doesn’t go on every page ? Just put this function __construct() in the controller main, which calls all its pages.

0


I decided using the Service Injection of Laravel 5.1.

In my sidebar.blade.php added:

@inject('categorias', 'App\Categoria')

@foreach($categorias->listar() as $categoria)
    <li>{{ $categoria->nome }}</li>
@endforeach

Documentation: http://laravel.com/docs/5.1/blade#service-Injection

Browser other questions tagged

You are not signed in. Login or sign up in order to post.