Ad

Laravel Model Is Only Returning Results Half Of The Time

- 1 answer

I have this method called show() which will fetch destinations from the database but it first checks for a location key in the input provided.

public function show()
{
  // Fetch the appropriate destinations
  if (Input::has('location')) {
    $destinations = Destination::where('type', '=', Input::get('type'))
      ->where('city', '=', Input::get('location'))
      ->with('city', 'state', 'type')
      ->get();
  } else {
    $destinations = Destination::where('type', '=', Input::get('type'))
      ->with('city', 'state', 'type')
      ->get();
  }
  \Log::debug($destinations);
  return $destinations;

This works perfectly fine, but only half the time. Sometimes it returns an empty array ([]) and sometimes it returns all of the results as expected.

At first I thought it was my JavaScript but it turns out logging this directly to the console from the PHP is also returning an empty array most of the time, but not always.

What would possibly cause something like this to happen?

Ad

Answer

First make sure you always pass exact same data (log also input data). For example one you pass "Hanover" and second time " Hanover" - it looks almost same, but will change results totally. So probably you should add trimming your data (if you are not doing it already).

Another potential issue is here:

$destinations = Destination::where('type', '=', Input::get('type'))
      ->where('city', '=', Input::get('location'))
      ->with('city', 'state', 'type')
      ->get();

Do you have city column in destinations table? If so, do you have also relationship with name city? It seems as error for me + in addition you should never create relationship with same name as column in table in database or you'll get into trouble sooner or later.

Ad
source: stackoverflow.com
Ad