skip to Main Content

in my laravel application I have a function that is ignoring a return, and it returns the RedirectResponse.
Hear my code.
This is the call:

public function updateReservationAPI(Booking $booking)
{
    try {
        $idReturned = $this->getReservationByDate($booking->arrival);
    } catch (Exception $e) {
        dd("Error on API call: " . $e->getMessage());
    }
}

And this is the code of the function:

private function getReservationByDate($date, $page = 1)
{
    $dateParam = Carbon::parse($date);
    $url = "https://api.site.url/api/reservations";
    $nextPage = "";

    if (Session::has('access_token')) {
        $client = new Client();
        $response = $client->get($url, [
            'headers' => [
                'Authorization' => 'JWT ' . Session::get('access_token'),
            ],
            'query' => [
                'page' => $page,
            ],
        ]);

        $statusCode = $response->getStatusCode();
        if ($statusCode === 200) {
            $body = $response->getBody()->getContents();
            $data = json_decode($body, true);

            $nextLink = $data["next"];
            if (!is_null($nextLink)) {
                $parsedUrl = parse_url($nextLink);
                parse_str($parsedUrl['query'], $queryParams);
                $nextPage = $queryParams['page'];
            }
            $results = $data['results'];

            $idToReturn = null;
            foreach ($results as $result) {
                $dataItem = Carbon::parse($result["register_date"]);

                if ($dateParam->isSameDay($dataItem)) {
                    $idToReturn = $result["id"];
                    return $idToReturn;
                }

            }
            if (!is_null($nextLink)) {
                return $this->getReservationByDate($date, $nextPage);
            }
        }

    } else {
        $this->loginAPI();
        $this->getReservationByDateAPI($date, $page);
    }
    return redirect()->back();
}

I would to return the id found on if ($dateParam->isSameDay($dataItem)) statement but I get an IlluminateHttpRedirectResponse response.

If I try to put dd($idToReturn) just before the return, I get the expected data.

2

Answers


  1. The problem is occurring because of the return redirect()->back(); statement that you have at the end of the function. This statement will always be executed if none of the conditions inside the function match, leading to a redirection.

    Login or Signup to reply.
  2. The issue is that your path leading to your ideal return is not true.

    So it will be one of these issues:

    • Session does not have access token
    • The status code of the request is not 200
    • Results is empty (so $data[‘results’] is empty or null)

    You can use dd() to dump the data at various points in the code to try and work out which one of those is returning false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search