Laravel 5, assuming variable in empty query?

2

I have a query, but sometimes this query returns an empty value ( no records ).

These query results are directed to the generation of a HighCharts chart, but when there are no values within the query, the graph is not generated.

My idea would be to set a if whenever the query returned empty, but I can not.

$vel_a2 = DB::table('ocorrencias')
      ->select(DB::raw('count(*) as qnt_cnt, velocidade'))
      ->where('cliente',$request->cliente)
      ->where('velocidade','=','A2')
      ->groupBy('velocidade')
      ->get();
if(empty($vel_a2))
{
   $vel_a2 = array('qnt_cnt'=> 0, 'velocidade'=>'A2');
}

Whenever the query is empty, it will assume a array to send to the chart.

    
asked by anonymous 17.11.2018 / 13:41

1 answer

0

When you use Query Builder to retrieve information from tables in your database, the result is always collection belonging to Illuminate \ Support \ Collection , in short is a class.

Whether this collection will contain record or not matters little because the result is always the instance of the class collection and so your verification is wrong, you should first check for a return and then check if you have items in your collection, example in your code:

if(is_null($vel_a2) || $vel_a2->count() == 0)
{
    $vel_a2 = array('qnt_cnt'=> 0, 'velocidade'=>'A2');
}

17.11.2018 / 21:51