Get first ancestor of page

Hi,

I am trying to work out how to get the first ancestor of a particular page. I am working on an online store, and as such have pages with a structure that look like this:

https://store.com/mens/clothing/t-shirts/long-sleeve/blue
https://store.com/womens/beanies/green
https://store.com/kids/sweatshirts-and-hoodies/hoodies/zipped/green

I want to be able to access that first ancestor of a page (e.g. ‘mens’, ‘womens’, ‘kids’) no matter how many levels down the page is from it. I know how to use ->parent() but as the amount of levels is unknown it won’t work here. I do know it will always be the first child of the url, but am not sure how to work with this.

Any help greatly appreciated!

I think this should work:

$page->parents()->last()

I think that should work too. If you chain ->slug() on the end that should give you just “womens” wheras ->url() will give you the full url to the page.

Brilliant - $page->parents()->last()->title() gave me exactly what I needed. Thanks both.