Laravel 5.0 Queries WhereIn

1

Good morning everyone

I have the following problem: from the url I pick up a id with which I make a query from which I take out an array. With this array I make another query to get the data I need in another table. The problem comes to me when displaying the data in the view, it only returns a value to me, while doing an echo from the foreach of the controller shows me all the values.

Driver

public function mostrarFacturas($id){
    $tienes = Tiene::where('idrc',$id)->select('idfactura')->get();     

    foreach ($tienes as $tiene => $valor) {
        $facturas = Factura::select('id' ,'nfactura', 'importe' ,'fecha')
        ->whereIn('id' , [$valor->idfactura])->get();
        echo $facturas;
        dd($facturas);
    }
    return view('rc.showFacturas' , [
        'tienes' => $tienes,
        'facturas' => $facturas ]);
}

Content template

    @extends('layouts.menuarea') 
    @section('content')

   @foreach($facturas as $factura)
   {{$factura}}
   @endforeach
   @stop

On the other hand if I make a dd ($ invoices) from the foreach I only receive a value.

Also I'm not sure I'm using the whereIn correctly. I appreciate any help.

    
asked by Peta P3t4d0r Zeta 17.01.2018 в 15:53
source

1 answer

0

Viewing only the code you have put, in the controller you are crushing the value of $facturas in each cycle of foreach

public function mostrarFacturas($id){
    $tienes = Tiene::where('idrc',$id)->select('idfactura')->get();     

    foreach ($tienes as $tiene => $valor) {
        //aqui se reasigna un vuevo valor en cada ciclo
        $facturas = Factura::select('id' ,'nfactura', 'importe' ,'fecha')
            ->whereIn('id' , [$valor->idfactura])->get();
        echo $facturas;
    }
    return view('rc.showFacturas' , [
        'tienes' => $tienes,
        'facturas' => $facturas ]);
}

The easiest way to fix it would be to set $facturas as an array

That is:

public function mostrarFacturas($id){
    $tienes = Tiene::where('idrc',$id)->select('idfactura')->get();     

    foreach ($tienes as $tiene => $valor) {
        //indicamos que se almacene en un array con los []
        $facturas[] = Factura::select('id' ,'nfactura', 'importe' ,'fecha')
            ->whereIn('id' , [$valor->idfactura])->get();
        //echo $facturas;
    }
    return view('rc.showFacturas' , [
        'tienes' => $tienes,
        'facturas' => $facturas ]);
}

On the other hand, if you define the relationships in the models, it is possible that this code is simplified using the methods that eloquent provides us.

You could review the documentation to adapt your models, link

    
answered by 17.01.2018 / 18:51
source