This episode is for members only

Sign up to access "Laravel Aggregates" right now.

Get started
Already a member? Sign in to continue
Playing
02. Aggregate aliasing

Transcript

00:00
So we saw earlier for this aggregate in particular that when we get that property out in the user model that gives us articles underscore count.
00:11
Now you might want to alias this at some point and any of the aggregates that we create within Laravel, whether they're counting or summing or any of the other stuff that we're going to look at in this series, we can actually alias these. So to do this we say articles and then as and then we give the alias name just here.
00:29
So for example articles as articles count and I can't think of a good name so I'm just going to call this articles count alias. So now when we come over instead of articles count we're going to have articles count alias. Let's go over give this a refresh and there we go. We get exactly the same thing.
00:47
You can see here in the query we're saying as at the end articles count alias. So Laravel will just take that, put it into the query as per that syntax that we've just used within the with count method and it will go ahead and alias this for you. So just bear this in mind through the rest of the series that you can alias any of your aggregates.

Episode summary

In this episode, we dive into how to alias aggregate columns in Laravel. We've already seen how Laravel gives us a default property name (like articles_count) when using aggregates, but sometimes you want to change this to something else that's more meaningful for your use case.

We walk through how easy it is to provide your own alias—just use the as keyword when specifying the aggregate in your query (for example, articles as articles_count_alias). Laravel will automatically update your query to use that alias, and when you access the property in your model, it'll have the name you specified.

Throughout this video, you'll see a live demo of updating the alias and confirming that it shows up as expected on both your models and in the SQL query itself. It's a handy feature, and you'll want to remember it as you add more aggregates to your queries. Alias away!

Episode discussion

No comments, yet. Be the first!