Back to overview

Easily inspect the contents of a Laravel collection

20 April 2023

Image of Freek

Freek

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.

Stay in the loop with updates & promotions for Ray

We only send a few emails a year.

Debug without breaking your flow

Ray keeps all your debug output neatly organized in a dedicated desktop app.

Licenses are valid for 1 year and managed through Spatie. Licenses purchased before Ray 3 remain valid. VAT is calculated at checkout.