Search code examples
vue.jslaravel-vue

How to display results in a laravel controller in Vue Template?


Please I have a return values in inside an array in a Laravel Controller. I want to display the in a Vue Template but am having Issue. I need Assistance please.

    public function search(Request $request)
    {  
      $batchResults = \DB::table('patient')
                            ->select('*')
                            ->join('registrations', 'patient.patient_id', 'registrations.patient_id')
                            ->where('patient.name', 'like', '%' . $request -> name . '%')
                            ->whereBetween('registrations.created_at', [date($request->from), date($request->to)])        
                            ->get();

                        $search = $request -> name;


                        return [ $batchResults, $batchResults ];



I want to dispaly [ $batchResults, $batchResults ] resut in vue Template

this is the console.log results

(2) [Array(1), "James Asay", __ob__: Observer]
0: [{…}, __ob__: Observer]
1: "James Asaye"
length: 2
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array

Vue Component

searchBatch(){
          axios.post('/search-results', this.form).then((res)=>{
            this.batchResource = res.data
            this.display = true

            console.log(res.data)
          })
        }

Solution

  • Allright, one useful strategy to debugging these sorts of problems, in your template add:

    <pre>{{$data}}</pre>
    

    So you can see all the data that is available to you in your template.

    As for why it isn't working. You receive batchResource from your server which is an array: [ $batchResult, $batchResult ],

    Either change your searchBatch function to adapt to this situation, like so:

    searchBatch(){
       axios.post('/search-results', this.form).then((res)=>{
      
       // res.data = [ $batchResult, $batchResult ]
       // take the first list of results:
       this.batchResource = res.data[0]
       this.display = true
    
       console.log(res.data)
       })
    }
    

    Or don't change the search function and deal with it in your template:

    <tr v-for="batch in batchResource[0]" :key="batch.id">
        <th scope="row">{{batch.patient_number}}</th>
        <td>{{batch.patient_name}} | {{batch.patient_gender}}</td>
    </tr>