Laravel 5, assuming variable in empty query?

Asked

Viewed 841 times

2

I have a query, but sometimes this query returns an empty value (off the books).

These query results are directed to generating a graph Highcharts, but when there are no values within the query, the graph is not generated.

My idea would be to ride a if whenever the query returned empty, but I’m not getting.

$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');
}

Every time the query was empty, it assumed a array to send to the chart.

1 answer

0


When using the Query Builder to rescue information from tables in your database the result is always a Collection belonging Illuminate Support Collection, summing up is a class.

Whether this collection will contain record or not matters little because the result is always the class instance Collection and so your checking is wrong, you should first check if there was a return and then check if there are 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');
}

References:

  • Thank you very much! It was very clear the explanation and it worked perfectly! Thanks for the friend help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.