Home > other >  Query for two models at once with Ajax - Eloquent - Laravel
Query for two models at once with Ajax - Eloquent - Laravel

Time:05-30

I would like to be able to list the records of two models at the same time, taking into account how I have the query set up at the moment to use it with Ajax.

Right now my query works fine, considering the rest of my project (AJAX - Laravel).

public function allData(){
        $data = Siniestro::orderBy('id','DESC')->get();
        return response()->json($data);
    }

I've tried doing it like this, but it looks like I'm doing the query wrong

public function allData(){
    $data = Siniestro::orderBy('id','DESC')->get();
    $users = User::all();
    return response()->json($data, $users);
}

Edit:

Esta es la vista que estoy refiriendo

This is the view; I want that with the eloquent query, it shows me ordered as now (orderBy), and also that it looks for a match of fields with "where"; for example $siniestros = Siniestro::where('estado', 'coordinado')->get();.

Edit 2

dd($users)

full view code

@extends('layouts.app')

@section('content')
    <section >
        <div >
            <h3 >Derivar IP</h3>
        </div>
        <div >
            <div >
                <div >
                    <div >
                        <div >                          
                                Inspecciones coordinadas                        
                        </div>
                        <div >
                            <table  style="width:100%">
                                <thead>
                                    <tr>
                                        <!-- <th scope="col">#</th> -->
                                        <th scope="col">Siniestro</th>
                                        <th scope="col">Fecha IP</th>
                                        <th scope="col">Modalidad</th>
                                        <th scope="col">Dirección</th>
                                        <th scope="col">Localidad</th>
                                        <th scope="col">Inspector</th>                                    
                                        <th scope="col">Acciones</th>
                                        
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table> 
                            
                            
                        </div>
                    </div>
                </div>
                <div  style="position:fixed; bottom:550px; right:0px">
                    <div >
                    <div >                          
                                <span id="addT">Asignar IP</span>
                                <span id="updateT">Asignar IP</span>                         
                        </div>
                        <div >
                                    

                                    <div >
                                        <div >
                                            <label for="inspector">Inspector</label>
                                            <input type="text" name="inspector"   id="inspector" for="inspector" >
                                            <span  id="instituteError"></span>
                                        </div>
                                    </div>


                                    <div >
                                    <label for="inspector">Inspector</label>
                                    <select  aria-label="Default select example" for="inspector" name="inspector" >
                                            <option selected></option>
                                            
                                            <option value="Taller del asegurado">Taller del asegurado</option>
                                            
                                        </select>
                                    </div>





                                    <div >
                                        <div >
                                                <label for="emailperito">E-mail</label>
                                                <input type="text" name="emailperito"   id="emailperito" for="emailperito">
                                        </div>
                                    </div>

                                    <div >
                                        <div >
                                                <label for="telefonoperito">Teléfono</label>
                                                <input type="text" name="telefonoperito"   id="telefonoperito" for="telefonoperito">
                                        </div>
                                    </div>

                                    

                                    

                                    <input type="hidden" id="id">
                                    
                                    <button type="submit" id="updateButton"  onclick="updateData(event)">Asignar</button>
                                                      
                                                        
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    

@endsection


@section('javas')

  <script>
    $(document).ready(function() {
    $('.tablita').DataTable({
        "serverSide": true,
        "ajax": "/teacher/all",
        "columns": [
            // {data: 'id'},
            {data: 'siniestro'},
            {data: 'fechaip'},
            {data: 'modalidad'},
            {data: 'direccion'},
            {data: 'localidad'},
            {data: 'inspector'},
            {data: 'action', name: 'action', orderable: true, searchable: true},
            
            

            
            
        ],

        
    });
})
</script>  

<script>



    





 $('#addT').hide();
 $('#addButton').hide();
 $('#updateT').show();
 $('#updateButton').show();

$.ajaxSetup({
    headers:{
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

//---------------------------------------------- Llamar datos de la BD ---------------------------------------------------------------

function allData(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/teacher/all",
        success: function (response){
            var data = ""
            $.each(response, function(key, value){
                data = data   "<tr>"
                // data = data   "<td>" value.id "</td>"
                data = data   "<td>" value.siniestro "</td>"
                data = data   "<td>" value.fechaip "</td>"
                data = data   "<td>" value.modalidad "</td>"
                data = data   "<td>" value.direccion "</td>"
                data = data   "<td>" value.localidad "</td>"
                data = data   "<td>" value.inspector "</td>"
                data = data   "<td>"
                data = data   "<button class='btn btn-info btn-sm' onclick='editData(" value.id ")'>Asignar IP</button>"
                data = data   "</td>"
                data = data   "</tr>"
            })
            $('tbody').html(data);
        }
    })
}

// --------------------------------------------- fin de llamar datos de la DB ----------------------------------------------------------

allData();

// --------------------------------------------- Limpiar los campos despues del submit -------------------------------------------------

function clearData(){
 $('#siniestro').val('');
 $('#fechaip').val('');
 $('#inspector').val('');
 $('#nameError').text('');
 $('#titleError').text('');
 $('#instituteError').text('');

}

// --------------------------------------------- fin de limpiar los campos despues del submit -------------------------------------------------

// --------------------------------------------- Agregar registros a la table de BD -------------------------------------------------


function addData(){
    var siniestro = $('#siniestro').val();
    var fechaip = $('#fechaip').val();
    var inspector = $('#inspector').val();

    $.ajax({
        type: "POST",
        dataType: "Json",
        data: {siniestro:siniestro, fechaip:fechaip, inspector:inspector},
        url:"/teacher/store/",
        success: function(data){
            allData();
            clearData();
            console.log('datos agregados con éxito');
        },

        error: function(error){
            $('#nameError').text(error.responseJSON.errors.name);
            $('#titleError').text(error.responseJSON.errors.title);
            $('#instituteError').text(error.responseJSON.errors.institute);
            
        }
    })

}

// --------------------------------------------- fin de agregar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Editar registros a la table de BD ---------------------------------------------------------

function editData(id){
    



 
      $.ajax({
          type:"get",
          dataType:"json",
          url:"/teacher/edit/" id,
          success: function(data){
             $('#addT').hide();
             $('#addButton').hide();
             $('#updateT').show();
             $('#updateButton').show();

              $('#id').val(data.id);
            //   $('#siniestro').val(data.siniestro);
            //   $('#fechaip').val(data.fechaip);
              $('#inspector').val(data.inspector);
             

              console.log(data);
          }
      })
 }

 // --------------------------------------------- Fin de editar registros a la table de BD -------------------------------------------------
 // --------------------------------------------- Update de registros a la table de BD -----------------------------------------------------



 function updateData(event){

    event.preventDefault();
     var id = $('#id').val();
    //  var siniestro =  $('#siniestro').val();
    //  var fechaip = $('#fechaip').val();
     var inspector = $('#inspector').val();

     $.ajaxSetup({
    headers:{
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})
     

     $.ajax({
         type: "PUT",
         dataType: "json",
         data: {inspector:inspector},
         url: "/teacher/update/" id,
         success: function(response){
            allData();
            clearData();
         console.log('Siniestro asignado con éxito');
         }
         
     })


 }

 


</script>
@endsection

Edit 3

enter image description here

See, the previous capture that showed me the attributes was only from $users, now using $data = Siniestro::orderBy('fechaip','ASC')->get();$users = User::all();$combo = ['users' => $users, 'data' => $data];dd($combo); As you can see, it shows me all the users, but I can't see their "attributes", strange, right? will the problem be there?

CodePudding user response:

json as a rule will always post an array, you can not post individual objects that way. you need to convert the objects into an array and post it.

$response_array['message'] = $data;
                $response_array['data'] = $users;
                return response()->json($response_array);

or

$data = ['users' => $users, 'content' => $contents]; return response()->json($data);

You can receive those data using :

success: function(response) {
console.log(response.content);
}

CodePudding user response:

So when you do

$data = Siniestro::orderBy('fechaip','ASC')->get();
$users = User::all();
$combo = ['users' => $users, 'data' => $data];

return response()->json($combo);

Then you should inspect the incoming response data in your javascript. As now the data is keyed by data and users. So in your allData() function in javascript you will have to adjust as per the keys to display the data.

function allData(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/teacher/all",
        success: function (response){

            //Here console.log(response) to see the structure of incoming data
            console.log(response)
            // Should output something like
            // {users: [... array of user records(objects)], data: [... array of siniestro records (objects)}
           
            // So to generate the display markup you may have to do
            $siniestroMarkup = "";
            $.each(response.data, function(key, value){
                siniestroMarkup = siniestroMarkup   "<tr>"
                siniestroMarkup = siniestroMarkup   "<td>" value.id "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.siniestro "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.fechaip "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.modalidad "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.direccion "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.localidad "</td>"
                siniestroMarkup = siniestroMarkup   "<td>" value.inspector "</td>"
                siniestroMarkup = siniestroMarkup   "<td>"
                siniestroMarkup = siniestroMarkup   "<td>"
                siniestroMarkup = siniestroMarkup   "<button class='btn btn-info btn-sm' onclick='editData(" value.id ")'>Asignar IP</button>"
                siniestroMarkup = siniestroMarkup   "</td>"
                siniestroMarkup = siniestroMarkup   "</tr>"
            })
            $('tbody').html(siniestroMarkup);
        });

            // Similarly you can access the user records
         $.each(response.users, function(key, value) {
            //Here value will represent each user record
         });

}

And you may also have to adjust the DataTable ajax response if you are using it probably like below (check exact response data structure for and how to access it for DataTable)

$(document).ready(function() {
    $('.tablita').DataTable({
        "serverSide": true,
        "ajax": "/teacher/all",
        "columns": [
            // {data: 'id'},
            {data: 'data.siniestro'},
            {data: 'data.fechaip'},
            {data: 'data.modalidad'},
            {data: 'data.direccion'},
            {data: 'data.localidad'},
            {data: 'data.inspector'},
            {data: 'data.action', name: 'action', orderable: true, searchable: true},              
        ],
    });
})

Check the above and see if that's how you want the data.

  • Related