can two functions be passed to a single view in laravel?

0

I am making a query in laravel but I want to solve this question, is it possible to do two functions and then return them to the same view?, if it can be done tell me how to do it please, I will leave the view and the controller so they can answer me

@extends('template.plantilla')
@section('content') 
<title>Pedidos Concentrado | Cercafe</title>
<style type="text/css">
    a>strong{
        font-weight: 700;
    }
    a:hover{ 
        text-decoration: none;
    }
    div.modal-header{
        background: red; 
    }
    div.modal-header>h3{
        color: white;
    } 
</style> 
<div class="panel panel-default"> 
    <input type="hidden" name="_token" value="{{ csrf_token() }}" id="token" required />
    <div class="panel-heading" id="titulo">
        <h4 style="font-size: 25px;"><i class="fa fa-list-alt" aria-hidden="true"></i> Nuevos Pedidos</h4>
    </div>
    <br>
    @if(Auth::User()->rol_id == 9)
        <div class="container-fluid col-xs-12 col-lg-12">
            {!!Form::open(['route'=> 'admin.filterConcentradoPedidos.store', 'class'=>'form-inline', 'method'=>'POST'])!!} 
                <div class="form-group">
                    <label>Desde:</label>
                    {!!Form::text('fecha_de',null, ['id' => 'date_picker_desde', 'class'=>'form-control', 'readonly', 'required', 'style' => 'cursor: pointer !important;'])!!}
                </div>
                <div class="form-group">
                    <label>Hasta:</label>
                    {!!Form::text('fecha_hasta',null, ['id' => 'date_picker_hasta', 'class'=>'form-control', 'readonly', 'required', 'style' => 'cursor: pointer !important;'])!!}
                </div>
                <div class="form-group">
                    {!! Form::select('granja', $granjas, array('0' => 'Seleccione una granja'), ['placeholder' => 'Selecciona una granja', 'class' => 'form-control col-xs-8' ]) !!}
                </div>
                <div class="form-group">
                    <select name="tipo" id="tipo" class="form-control col-xs-8">
                        <option value=" ">Formato de Busqueda</option>
                        <option value="pd">Pedidos</option>
                        <option value="pr">Productos</option>
                    </select>
                </div>
                <div class="form-group">
                    {!!Form::submit('Buscar', array('class'=>'btn btn-success'))!!}
                </div>
            {!! Form::close() !!}
            <div class="form-group pull-right"> 
                <a href="javascript:history.go(-1);" class="btn btn-info"><i class="fa fa-arrow-left" aria-hidden="true"></i> Regresar</a>
                <a href="{{ route('admin.entregaconcentrados.index')}}" class="btn btn-warning"><i class="fa fa-clock"> </i> Asignar Turno</a>
            </div> 
        </div>
    @endif 
    <script type="text/javascript">
        pedido = [];
        @foreach($pedidos as $pedido)
            var estado = {{$pedido->estado_id}};
            var consecutivo = {{$pedido->consecutivo}};
            item = {}
            item["estado"] = estado;
            item["consecutivo"] = consecutivo;
            pedido.push(item);  
        @endforeach
        pedido["pedido_concentrados"] = pedido;
    </script>
    <div class="panel-body table-responsive"> 
        <table id="data_list" class="table table-bordered table-hover text-center" cellspacing="0" width="100%"> 
            <thead style="background-color: #df0101;">
                <tr style="color: white;">
                    <td><strong>Consecutivo</strong></td>
                    <td><strong>Granja</strong></td>
                    <td><strong>Fecha de Creación</strong></td>
                    <td><strong>Fecha Estimada</strong></td>
                    <td><strong>Estado</strong></td>
                    <td><strong>Fecha de Entrega</strong></td>
                    <td><strong>Conductor</strong></td>
                    <td><strong>Vehiculo</strong></td>
                    <td><strong>Documentacion</strong></td>
                </tr>
            </thead>
            <tbody> 
                @if(Auth::User()->rol_id == 10)
                    @foreach($g_as as $g)
                        @if($g->user_id == Auth::User()->id)
                            @foreach($pedidos as $pedido)
                                @if($g->granja_id == $pedido->granja_id)
                                    @if($pedido->fecha_entrega == 'por verificar' || $pedido->conductor_asignado == 'por verificar' || $pedido->vehiculo_asignado == 'por verificar')
                                        <script type="text/javascript">
                                            $(document).ready(function () 
                                            {
                                                $("#modificar_f_concentrados{{$pedido->id}}").datepicker(
                                                { 
                                                    changeMonth: true,
                                                    changeYear: true,
                                                    yearRange: "1950:2100",
                                                    dateFormat: "yy-mm-dd", 
                                                    showButtonPanel: true,
                                                });
                                            })
                                            function enviarCampos(id)
                                            {
                                                var modificar = [];
                                                var consecutivo = id;
                                                var entrega = document.getElementById("modificar_f_concentrados{{$pedido->id}}").value;
                                                var conductor = document.getElementById("cd{{$pedido->id}}").value;
                                                var vehiculo = document.getElementById("vh{{$pedido->id}}").value;

                                                console.log(consecutivo + " " + entrega + " " + conductor + " " + vehiculo);

                                                item = {}
                                                item["cons"] = consecutivo;
                                                item["fecha"] = entrega;
                                                item["cond"] = conductor;
                                                item["placa"] = vehiculo;

                                                modificar.push(item); 

                                                modificar["modificar_concentrados"] = modificar;

                                                console.log(modificar);
                                                var token = $("#token").val(); 
                                                $.ajax({
                                                    type: "POST",
                                                    headers: {'X-CSRF-TOKEN': token},
                                                    url: "http://201.236.212.130:82/intranetcercafe/public/admin/modificarPedidoC", 
                                                    dataType: 'json',
                                                    data: {data: JSON.stringify(modificar)}
                                                });
                                                swal({
                                                    title:'Pedido Modificado Satisfactoriamente.',
                                                    text:'',
                                                    type:'info',
                                                    showCancelButton:false,
                                                    confirmButtonClass:'btn-primary',
                                                    confirmButtonText:'Recargar'
                                                },
                                                function(isConfirm)
                                                {
                                                    if (isConfirm) 
                                                    {
                                                        location.reload();
                                                    }
                                                });   
                                            }
                                        </script>
                                        <tr>
                                            <td>
                                                <a href="{{ route('admin.pedidoConcentrados.show', $pedido->consecutivo) }}" data-toggle="modal" data-target="#myModal">
                                                    <strong>PCO{{ $pedido->consecutivo }}</strong>
                                                </a>
                                            </td>
                                            <td>{{ $pedido->nombre_granja }}</td>
                                            <td>{{ $pedido->fecha_creacion }}</td>
                                            <td>{{ $pedido->fecha_estimada }}</td>
                                            <td><strong style="color: #FDAE05;"> En Tramite </strong></td>
                                            <td>
                                                <strong>
                                                    <input id="modificar_f_concentrados{{$pedido->id}}" class="form-control" type="text" name="fecha" value="{{ $pedido->fecha_entrega }}" readonly />
                                                </strong>
                                            </td>
                                            <td>
                                                <select name="conductor" class="form-control" id="cd{{$pedido->id}}" selected="selected" />
                                                    @if($pedido->conductor_asignado == 'por verificar')
                                                        <option value="por verificar">{{ $pedido->conductor_asignado }}</option>
                                                        @foreach($conduct as $c)
                                                            <option value="{{$c->id}}">{{$c->nombre}}</option>
                                                        @endforeach
                                                    @else
                                                        @foreach($conduct as $c)
                                                            @if($pedido->conductor_asignado == $c->nombre)
                                                                <option value="{{$c->id}}">{{$c->nombre}}</option>
                                                            @endif
                                                        @endforeach
                                                        @foreach($conduct as $c)
                                                            <option value="{{$c->id}}">{{$c->nombre}}</option>  
                                                        @endforeach
                                                    @endif
                                                </select>
                                            </td>
                                            <td>
                                                <select name="vehiculo" class="form-control" id="vh{{$pedido->id}}" selected="selected">
                                                    @if($pedido->vehiculo_asignado == 'por verificar')
                                                        <option value="por verificar">{{ $pedido->vehiculo_asignado }}</option>
                                                        @foreach($vehicul as $v)
                                                            <option value="{{$v->id}}">{{$v->placa}}</option>
                                                        @endforeach
                                                    @else
                                                        @foreach($vehicul as $v)
                                                            @if($pedido->vehiculo_asignado == $v->placa)
                                                                <option value="{{$v->id}}">{{$v->placa}}</option>
                                                            @endif
                                                        @endforeach
                                                        @foreach($vehicul as $v)
                                                            <option value="{{$v->id}}">{{$v->placa}}</option>
                                                        @endforeach
                                                    @endif
                                                </select>  
                                            </td>
                                            <td>
                                                <a href="#" class="btn btn-primary" id="validar" onclick="enviarCampos({{ $pedido->consecutivo }});"><i class="fa fa-check"></i> Validar</a>
                                            </td>
                                        </tr>
                                    @endif
                                @endif
                            @endforeach
                        @endif
                    @endforeach
                @elseif(Auth::User()->rol_id == 6)
                    @foreach($g_as as $g) 
                        @if($g->user_id == Auth::User()->id)
                            @foreach($pedidos as $pedido)
                                @if($pedido->estado_id == 2)
                                    @if($g->granja_id == $pedido->granja_id)
                                        <tr>
                                            <td>
                                                <a href="{{ route('admin.pedidoConcentrados.show', $pedido->consecutivo) }}">
                                                    <strong>PCO{{ $pedido->consecutivo }}</strong>
                                                </a>
                                            </td>
                                            <td>{{ $pedido->nombre_granja }}</td>
                                            <td>{{ $pedido->fecha_creacion }}</td>
                                            <td>{{ $pedido->fecha_estimada }}</td>
                                            <td><strong style="color: #8BC34A;"> Tramitado </strong></td>
                                            <td>
                                                <strong>
                                                    {{ $pedido->fecha_entrega }}
                                                </strong>
                                            </td>
                                            <td>
                                                {{ $pedido->conductor_asignado }}</option>
                                            </td>
                                            <td>
                                                {{ $pedido->vehiculo_asignado }}
                                            </td>
                                            <td>
                                                <a href="/intranetcercafe/public/admin/excelPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-success"><i>{!!Html::image('c.png','us',array('class' => 'imuser'))!!} </i></a>
                                                <a href="/intranetcercafe/public/admin/pdfPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-danger"><i>{!!Html::image('pdf.png','us',array('class' => 'imuser'))!!} </i></a>
                                            </td>
                                        </tr>   
                                    @endif
                                @endif
                            @endforeach
                        @endif
                    @endforeach
                @elseif(Auth::User()->rol_id == 9)
                    @foreach($pedidos as $pedido)
                        @if($pedido->estado_id == 2)
                            <tr>
                                <td>
                                    <a href="{{ route('admin.pedidoConcentrados.show', $pedido->consecutivo) }}">
                                        <strong>PCO{{ $pedido->consecutivo }}</strong>
                                    </a>
                                </td>
                                <td>{{ $pedido->nombre_granja }}</td>
                                <td>{{ $pedido->fecha_creacion }}</td>
                                <td>{{ $pedido->fecha_estimada }}</td>
                                <td><strong style="color: #8BC34A;"> Tramitado </strong></td>
                                <td>
                                    <strong>
                                        {{ $pedido->fecha_entrega }}
                                    </strong>
                                </td>
                                <td>
                                    {{ $pedido->conductor_asignado }}</option>
                                </td>
                                <td>
                                    {{ $pedido->vehiculo_asignado }}
                                </td>
                                <td>
                                    <a href="/intranetcercafe/public/admin/excelPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-success"><i>{!!Html::image('c.png','us',array('class' => 'imuser'))!!} </i></a>
                                    <a href="/intranetcercafe/public/admin/pdfPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-danger"><i>{!!Html::image('pdf.png','us',array('class' => 'imuser'))!!} </i></a>
                                </td>
                            </tr>
                        @endif
                    @endforeach
                @endif
            </tbody>
        </table>        
    </div>
</div>
@if(Auth::User()->rol_id == 10)
    <div class="panel panel-default">
        <div class="panel-heading" id="titulo">
            <h4 style="font-size: 25px;"><i class="fa fa-list-alt" aria-hidden="true"></i> Historial</h4>
        </div>
        <div class="panel-body table-responsive">
            <table id="data_list_estados" class="table table-bordered table-hover text-center" cellspacing="0" width="100%"> 
                <thead style="background-color: #df0101;">
                    <tr style="color: white;">
                        <td><strong>Consecutivo</strong></td>
                        <td><strong>Granja</strong></td>
                        <td><strong>Estado</strong></td>
                        <td><strong>Fecha de Entrega</strong></td>
                        <td><strong>Conductor</strong></td>
                        <td><strong>Vehiculo</strong></td>
                        <td><strong>Documentacion</strong></td>
                    </tr>
                </thead>
                <tbody> 
                    @foreach($g_as as $g)
                        @if($g->user_id == Auth::User()->id)
                            @foreach($pedidos as $pedido)
                                @if($g->granja_id == $pedido->granja_id)
                                    @if($pedido->estado_id  == 2)
                                        <tr>
                                            <td>
                                                <a href="{{ route('admin.pedidoConcentrados.show', $pedido->consecutivo) }}">
                                                    <strong>PCO{{ $pedido->consecutivo }}</strong>
                                                </a>
                                            </td>
                                            <td>{{ $pedido->nombre_granja }}</td>
                                            <td><strong style="color: #8BC34A;"> Tramitado </strong></td>
                                            <td>
                                                <strong>
                                                    {{ $pedido->fecha_entrega }}
                                                </strong>
                                            </td>
                                            <td>
                                                {{ $pedido->conductor_asignado }}</option>
                                            </td>
                                            <td>
                                                {{ $pedido->vehiculo_asignado }}
                                            </td>
                                            <td>
                                                <a href="/intranetcercafe/public/admin/excelPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-success"><i>{!!Html::image('c.png','us',array('class' => 'imuser'))!!} </i></a>
                                                <a href="/intranetcercafe/public/admin/pdfPedidoConcentrados/{{$pedido->consecutivo}}" class="btn btn-danger"><i>{!!Html::image('pdf.png','us',array('class' => 'imuser'))!!} </i></a>
                                            </td>
                                        </tr>
                                    @endif
                                @endif
                            @endforeach
                        @endif
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
@endif
{{-- <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header" id="titulo">
            <h4 style="font-size: 25px;"><i class="fa fa-list-alt" aria-hidden="true"></i> PCO{{$consecutivo}}</h4>
        </div>
        <div class="modal-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover text-center" cellspacing="0" width="100%">
                    <thead> 
                        <tr style="color: white;">
                            <td><strong>Nombre de la Granja</strong></td>
                            <td><strong>Nombre del Concentrado</strong></td>
                            <td><strong># Bultos</strong></td>
                            <td><strong># Kilos</strong></td>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($productos_db as $producto_db)
                            <tr>
                                <td>{{$producto_db["granja"]}}</td>
                                <td>{{$producto_db["concentrado"]}}</td>
                                <td>{{$producto_db["bultos"]}}</td>
                                <td>{{$producto_db["kilos"]}}</td>
                            </tr>
                        @endforeach 
                    </tbody>
                </table>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
</div>
--}}</div>
@endsection

this is the code of the controller, the index function makes it load the data once the page is loaded

public function index()
{
    $conduct = Conductor::all();
    $g_as = AsociacionGranja::all();
    $vehicul = VehiculoDespacho::all();
    $granjas = Granja::lists('nombre_granja', 'id');
    $conductores = Conductor::lists('nombre', 'id');
    $vehiculos = VehiculoDespacho::lists('placa', 'id');
    $pedidos_c = DB::table('consecutivos_concentrados') 
            ->join('granjas', 'consecutivos_concentrados.granja_id', '=', 'granjas.id')
            ->select('consecutivos_concentrados.*', 'granjas.nombre_granja')
            ->orderBy('consecutivo', "desc")
            ->get();
    return view('admin.pedidos.consultar_pedido_concentrados', compact('granjas', $granjas, 'conductores', $conductores, 'vehiculos', $vehiculos, 'conduct', $conduct, 'vehicul', $vehicul,'g_as',$g_as))->with('pedidos', $pedidos_c);  
}

While this function loads me the modal that is commented because when the page is loaded it generates an error saying that the consecutive variable was not defined

public function show($consecutivo)
{
    $productos = PedidoConcentrado::all();
    $granjas = Granja::all();
    $concentrados = Concentrado::all();
    $seleccionados =  [];

    foreach ($productos as $producto) 
    {
        if ($producto->consecutivo_pedido == $consecutivo) 
        {
            foreach ($granjas as $granja) 
            {
               if ($granja->id == $producto->granja_id) 
               {
                   foreach ($concentrados as $concentrado) 
                   {
                        if($concentrado->id == $producto->concentrado_id)
                        {
                            $productos_db[$producto->id]["granja"] = $granja->nombre_granja;
                            $productos_db[$producto->id]["concentrado"] = $concentrado->nombre_concentrado;
                            $productos_db[$producto->id]["bultos"] = $producto->no_bultos;
                            $productos_db[$producto->id]["kilos"] = $producto->no_kilos;
                        }
                   }
               }
            }
        }
    } 
    if ( !empty($productos_db) && is_array($productos_db))
    {
        return view('admin.pedidos.consultar_pedido_concentrados', compact('consecutivo', $consecutivo))->with('productos_db', $productos_db);
    }
    else
    {
        flash('<strong>Ha Ocurrido un Error con este Pedido!!!</strong>')->error()->important();
        return redirect()->route('admin.pedidoConcentrados.index');
    }  
}

then my question is, can two functions be sent to the same view ????

    
asked by Juan Esteban Yarce 24.04.2018 в 22:30
source

1 answer

0

The truth is that your code is difficult to read and I do not understand very well what you want to do. Be sure to optimize it because it will help you in the future.

Comment: Those foreach you can eliminate by adding the corresponding relation to your Product model.

The Product model

class Producto extends Model
{
    protected $fillable = [
        'id','no_bultos','no_kilos','concentrado_id','granja_id','consecutivo_pedido'
    ];

    public function concentrado()
    {
        return $this->belongsTo('App\Concentrado', 'concentrado_id');
    }
    public function granja()
    {
        return $this->belongsTo('App\Granja', 'granja_id');
    }
}

On the controller

public function show($consecutivo)
{
    $producto = Producto::with(['concentrado', 'granja'])
                         ->where('consecutivo_pedido',$consecutivo)
                         ->first();
    return view('admin.pedidos.consultar_pedido_concentrados')
             ->with('productos_db', $producto);
    // En este caso por ejemplo para acceder al nombre de la granja 
    // en la vista tendrias que hacer 
    // $producto->granja->nombre_granja 
    // y lo mismo con concentrado
}

To answer your question:

1- I divided the views based on the requirements that each one needs.
    (Eg listado_de_productos.blade.php and listados_de_granjas.blade.php )

2- Create a view composer for each view in the app / Providers / AppServiceProvider.php file within the boot() method (You can also create a Service Provider only for the view composers).

public function boot() {
  /**
   * Este View Composer envía el listado de todos los productos
   * a la vista de listado de productos
   * en la variable $productos
   */
  view()->composer('listado_de_productos', function($view) {

    // Podés hacer la consulta que quieras yo usé all() para simplificar.
    $productos = \App\Producto::all(); 
    // También podés enviar datos estáticos 
    // $productos = ['producto1','producto2','producto3' ];

    $view->with('productos', $productos);
  });

  /**
   * Este View Composer envía el listado de todas las granjas
   * a la vista de listado de granjas
   * en la variable $granjas
   */
  view()->composer('listados_de_granjas', function($view) {
        $granjas = \App\Granja::all();   
        $view->with('granjas', $granjas);
  });

}

More info on this link

In this link you will find more detailed information about the options you have available.
For example:

  • If the view is a subfolder it works the same as in the controller (more points): composer('subcarpeta.listado_de_productos', ...)
  • If you need to share information with multiple views, replace the name of the view with an array of view names: composer(['listado_de_productos', 'listado_de_granjas'], ...)
  • If you need to share information with all views set a * : composer('*', ...)

Added in response to your comment y como podria mandar los dos arrays a la misma vista ?? – Juan Esteban Yarce el 24 abr. a las 21:20 To pass 2 variables to a view you can do it from the following handles

public function show($consecutivo)
{
    $productos = Producto::all();
    $granjas = Granja::all();
    return view('NOMBRE_DE_LA_VISTA')
             ->with('productos', $productos)
             ->with('granjas', $granjas);
}

I hope this helps you,
greetings
Maru

    
answered by 01.05.2018 в 14:22