1

I am very new to the laravel framework and i have what it seems to be a simple question. I have a query like so

 $query['query2']= DB::connection('test')->select(
"select * from cities");
 ...
 ...
 echo json_encode($q);

Sometimes this particular query returns an empty result set. How do I handle this? Lets say I want to add my own json response when its empty. Thanks

1 Answer 1

2

Try the following

 $dataToSend = $q->get(); // $q being your query

 if($dataToSend->isEmpty())
 {
   echo json_encode(['something'=>'else']);
 }
 else
 {
   echo json_encode($dataToSend);
 }

Or in a shorter fashion

 $dataToSend = $q->get(); // $q being your query

 echo json_encode($dataToSend->isEmpty()? ['something'=>'else'] : $dataToSend);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.