Check if the object is a page or collection

I needed to figure out if an object was a page or a collection.

In the example below it uses a random page from the collection if it’s a collection or use the page if it’s a page object.

$collection = page('projects')->children();
//$collection = page('home');

if( $collection->slug() ) {
  $page = $collection;
} elseif( $collection->count() > 1 ) {
  $page = $collection->shuffle()->first();
}

echo $page->title();

It’s probably possible to improve this code a bit with more clever solutions. If so, bring it!

Update

Here is the same thing improved with code by @texnixe.

$collection = page('projects')->children();
//$collection = page('home');

if( is_a($collection, 'Collection' )) {
  $page = $collection->shuffle()->first();
} elseif( $collection ) {
  $page = $collection;
}

echo $page->title();

You can use is_a() to check if an object is of a certain type:

<?php
if(is_a($collection, 'Collection')) {
echo "Yay, it's a collection";
}
1 Like

Nice! I’ve added an updated example above. Thanks! :slight_smile: