Articles search by category Laravel 5.3

0

Good evening, I'm trying to get the categories and their respective articles. I would like the name of the category to appear in the view as a title and then each of your articles appear:

For example:

COMPUTATION: keyboard, mouse, laptop

VEHICLES: truck, car

... and thus of each category

I have the following driver but I'm not sure it's like this:

$articulos=DB::table('articulo as art')
->join('categoria as cat','art.idcategoria','cat.idcategoria')
->select('cat.nombre as categoria','art.nombre as articulo')
->get();
return view('almacen.articulo.index',["articulos"=>$articulos]);

And the view would be:

@foreach($articulos as $art)
	
	{{$art->categoria}}

		//Aqui otro @foreach???

@endforeach

If someone could help me ... thanks in advance.

    
asked by Anddy Cabrera Garcia 24.02.2017 в 03:58
source

2 answers

2

You must use a foreach inside the main foreach. in your Controller

$categorias = Categoria::orderBy('id', 'DESC')->all(); 

in your view:

@foreach ($categorias as $categoria)
   {{ $categoria->nombre }}
   @foreach ($categoria->articulos as $articulos)
        {{ $articulos->nombre }}
   @foreach
@endforeach
    
answered by 26.02.2017 в 15:37
0

From my point of view I think that you are addressing the problem in the inverse way, because your point of reference or initial seem to be the categories:

Although I do not agree with making queries from the controller, but to make the example faster, I will do it according to your structure, assuming you have a model Categoria with the defined relation towards another model called Articulo :

$categorias = Categoria::with('articulos')->get();

return view('...', compact('categorias'));

In the view (this code can be improved and is not tested):

@foreach ($categorias as $categoria)

    {{ $categoria->nombre }}:

    @foreach ($categoria->articulos as $index => $articulo)

        @php $nombres[] = $articulo->nombre @endphp

    @endforeach

    @if (isset($nombres))
        {{ implode(', ', $nombres) }}
    @endif

@endforeach

To help you understand a little more about relationships in Laravel, check out: link

    
answered by 24.02.2017 в 17:07