Trying to get property of non-object - retrieve set of data in laravel 5.0

- 1 answer

Ad

I'm having this issue with laravel when I'm getting data from two tables.This is my query. It exists in a controller.

$switches = DB::table('sw_pairs')->
   join('cust_sw_pair','cust_sw_pair.sw_pair_id', '=', 'sw_pairs.sw_pair_id')->
   select(
        DB::raw(
                'cust_sw_pair.sw_pair_id,  
                 count(cust_sw_pair.sw_pair_id) as totcount, 
                 pri_sw, sec_sw, 
                 count(if(pri_sw_admin_status="Admin Down" AND sec_sw_admin_status="Admin Down", 1, NULL)) as downCount')
         )->
   groupBy('cust_sw_pair.sw_pair_id')->get();

When I execute this query I get this error.

"Trying to get property of non-object"

but the above query is succesfully returning the first row of the result set when I used first() instead of the get() method.

This is the retrieving part which exists on the view:

@foreach($switches as $switch_pair)  
   <tr>  
   <td>{{$switches->pri_sw}} / {{$switches->sec_sw}}</td>  
   <td><span>{{$switches->downCount}},{{$switches->totcount}</span></td>  
   <td><i class="fa fa-level-up"></i> 40% </td>  
   <td>{{$switches->downCount}} / {{$switches->totcount}}</td></tr>  
@endforeach  

How can I successfully get all the results?

Ad

Answer

Ad

There are two problems with your code:

  • a) you are looping through $switches but are not using the single items within the loops
  • b) missing accolade in the second td

So to give you the result of the above fixed:

@foreach($switches as $switch_pair)  
   <tr>  
   <td>{{ $switch_pair->pri_sw }} / {{ $switch_pair->sec_sw }}</td>  
   <td><span>{{ $switch_pair->downCount }},{{ $switch_pair->totcount }}</span></td>  
   <td><i class="fa fa-level-up"></i> 40% </td>  
   <td>{{ $switch_pair->downCount }} / {{ $switch_pair->totcount }}</td></tr>  
@endforeach 
Ad
source: stackoverflow.com
Ad