0

El problema que tengo es que el foreach en un controlador (para crear un pdf) y no me funciona

 $datos_integrantes = S_Solicitud_Integrante_Persona::where('id_solicitud', '=', $datos->id_solicitud)->get();

escribir($datos, $datos_integrantes));

  public function escribir($datos, $integrante)
    {
        
        return " <section style='margin-top: 10px;'>
        <div align='left'>
            <table width='100%'>
               @foreach ($integrante as $integrante)
                        <tr>
                            <td> ".$integrante->apellido." ".$integrante->nombre." </td>
                        </tr>
                        @endforeach 
         </table> </div> </section>"; }

El error que me tira es: Property [apellido] does not exist on this collection instance. Ahora bien, si utilizo otra variable:

                            @foreach ($integrante as $inte)
                        <tr>
                            <td> ".$inte->apellido." ".$inte->nombre." </td>
                        </tr>
                        @endforeach

Dice Undefined variable: inte. Intente hacerlo manualmente, sin usar bucle, y anda:

.$integrante[0]->apellido." ".$integrante[0]->nombre."
.$integrante[1]->apellido." ".$integrante[1]->nombre."

Pero necesito el bucle, y no entiendo por qué el foreach no funciona, nunca me habia pasado! Gracias

1 respuesta 1

1

No puedes retornar la plantilla como un string desde el controlador. Debes crear un archivo de plantillas .blade.php con ese contenido y pasarle solo $integrante como parámetro para que blade pueda interpretar el @foreach durante la compilación.

Ejemplo:

// plantilla.blade.php
<section style='margin-top: 10px;'>
    <div align='left'>
        <table width='100%'>
        @foreach ($integrante as $inte)
            <tr>
                <td> {{ $inte->apellido }} {{ $inte->nombre }} </td>
            </tr>
        @endforeach 
        </table>
    </div>
</section>
// Controlador
return view('ruta/plantilla', ['integrante' => $integrante]);

o también

// Controlador
return view('ruta/plantilla', compact('integrante'));

Como lo tienes actualmente, lo único que estás haciendo es retornar un string que busca concatenar el arreglo integrante como si fuese un string (ya ahí tienes un error), y luego concatenas además la propiedad apellido de la variable $int que no está declarada. No se está ejecutando ningún foreach.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.