Laravel 5: Conditionally Transforming/Changing Values With transform

Laravel 5

The transform helper function is used to modify the provided value if the value contains a "non-empty" value. A value is considered to be "empty" or "blank" if it meets one of the following conditions:

  • The value is null,
  • The value is a string and contains only whitespace or is of length 0,
  • The value is not numeric,
  • The value is not a boolean value,
  • The value is a Countable object and contains no items,
  • The the PHP empty evaluates to true

If the provided value is not empty, it will be passed as an argument to the the $callback parameter and the results returned. If the value is empty, the value supplied for the $default parameter will be returned, which itself can be an anonymous function.

Signature

The signature of the transform method is:

function transform(
    $value,
    callable $callback,
    $default = null
);

Example Use

In the with helper function section we implemented a getWeatherForecast function that will return the forecast for a provided location. However, that implementation does not take into account when the Yahoo weather API returns an empty forecast, either because the API call failed, or the user supplied an invalid location.

We could handle this using a variety of if control statements, but we will use the transform helper function to help us control the output of the getWeatherForecast function when these situations arise:

/**
 * Returns a weather forecast for a given place.
 *
 * @param string $place
 * @return \Illuminate\Support\Collection
 */
function getWeatherForecast($place) {
    return with($place, function ($place) {
        $apiUrl = 'https://query.yahooapis.com/v1/' .
        'public/yql?q=select%20*%20from%20weather.' .
        'forecast%20where%20woeid%20in%20(select'   .
        '%20woeid%20from%20geo.places(1)%20where'   .
        '%20text%3D%22<PLACE>%22)&format=json&env=' .
        'store%3A%2F%2Fdatatables.org' .
        '%2Falltableswithkeys';

        $apiUrl = str_replace(
                    '<PLACE>',
                    $place,
                    $apiUrl
                  );

        return with(
            new GuzzleHttp\Client,
            function ($client) use ($apiUrl) {
                /** @var GuzzleHttp\Client $client */
                $response     = $client->get($apiUrl);
                $responseBody = $response->getBody();
                $result       = json_decode(
                                    $responseBody
                                    ->getContents()
                                );

                // Get the forecast. We will use the
                // the transform function to help
                // return an empty collection
                // for no forecast results.
                return transform(
                    $result->query->results,

                    // Return API forecast.
                    function ($results) {
                        return collect(
                            $results->channel
                                    ->item
                                    ->forecast
                        );
                    },

                    // Return empty collection.
                    function ($results) {
                        return collect();
                });
        });
    });
}

Start the Discussion

Leave a comment

Subscribe to our newsletter