20 April 2023
Freek
Easily inspect the contents of a Laravel collection
One of my favorite things when working on a Laravel project is Laravel's powerful Collection class. I use it all of the time to transform data.
Let's take a look at a straightforward example. You'll see longer collection chains with more complicated methods in real-world applications.
collect(['a', 'b', 'c'])
->map(fn(string $letter) => strtoupper($letter))
->reverse();
Imagine you want to see what the collection's contents look like in the middle of the chain in Ray. You might do something like this.
$collection = collect(['a', 'b', 'c'])
->map(fn(string $letter) => strtoupper($letter));
ray($collection);
$collection->reverse();
That will work: the collection's contents will be displayed in Ray.
But going about it this way is a lot of work: you have to introduce a new temporary variable and break up your chain.
Luckily there's a much simpler way of going about this. When the spatie/laravel-ray package is installed in your Laravel project, we automatically register a ray
collection macro to easily send collections to the desktop application. So to see what the collection looks like, you can simply add a ray()
call after that map
operation.
collect(['a', 'b', 'c'])
->map(fn(string $letter) => strtoupper($letter))
->ray()
->reverse();
Of course, you can use ray()
multiple times in your chain, and you can even pass it a label which will be displayed in Ray.
collect(['a', 'b', 'c'])
->ray('original')
->map(fn(string $letter) => strtoupper($letter))
->ray('uppercased')
->reverse()
->ray('reversed');
And that's how easy it is to inspect collections in Ray.
Understand and fix bugs faster
Ray is a desktop application that serves as the dedicated home for debugging output. Send, format and filter debug information from both local projects and remote servers.