Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nilsringersma's avatar

Collection orderBy url ignore protocol and www subdomain

Hello everyone,

I'm working on a project where I'm retrieving a collection. The model I'm retrieving has a property url where an url is stored. This url can be something like https://laracasts.com or http://laracast.com or https://www.laracasts.com.

I am ordering and paginating the collection using $models->orderBy('url', 'ASC')->paginate(); which is working as expected however I would like to order my collection on the url field whilst ignoring the http or https protocol and www subdomain. It is essential that pagination will still work.

Could anyone offer me some advise on how to accomplish this? Thanks in advance :)!

0 likes
4 replies
MarianoMoreyra's avatar
Level 25

@nilsringersma try this sample query directly on your database and see if it's what you may be needing:

SELECT REGEXP_REPLACE('https://www.laracasts.com','http://|https://|www.','',1,0,'c') as URL order by URL;

In your case you can replace 'https://www.laracasts.com' with the url field of your table.

Here you have a working example: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=92920e3ec2af40fc82283fed80d8e420

Let me know if this worked for you!

1 like
siangboon's avatar

to get the host name, you can try this:

return parse_url(request()->root())['host']; 

https://www.php.net/manual/en/function.parse-url.php

but I'm not sure how to remove the subdomain as it is not easy, the subdomain can be www2. or without the www, or multiple level subdomains, and the root domain can be .com, .my, .net.my...

1 like
nilsringersma's avatar

Hi @siangboon and @marianomoreyra . Thanks for your advise! Both answers resulted in a fix. I've improved my app by storing the 'nicename' for the URL in a new property for my model. This way I don't have to replace it on runtime for each request.

Thanks for the help :)!

Please or to participate in this conversation.