I am studying the source code of a package, rtConner/laravel-tagging. In this package there is a trait called TaggableTrait. On line 179, in a method called addTag(), there is this line which I don't understand:
$previousCount = $this->tagged()->where('tag_slug', '=', $tagSlug)->take(1)->count();
What does this line do? In specific, my problem is with
->take(1)->count(); part, are we taking 1 of the entries from the where clause and then count it?
Best How To :
From the Laravel documentation:
Alias to set the "limit" value of the query.
So basically what you do is constructing a query with Query Builder and you are literally saying:
Select count of all tags, where tag_slug is $tagSlug and return the first row
It is equal to
SELECT COUNT(*) FROM tags WHERE tag_slug = 'blabla' LIMIT 1
Since COUNT() is aggregate function it will always return one row (count of all rows that match the where condition), so
->take(1) is obselote and will give you the same result with or without it.