John Davidson

php - Recursive function count In laravel


Please help me out with the Recursive function in the model, I want a count on multilevel subcategories.

$userChild = Referral::with(['get_children'])->where('user_id',Auth::id())->get();

My Answer:
> Here is an example of a recursive function in a Laravel model to count multilevel subcategories:

class Referral extends Model
public function get_children()
return $this->hasMany(Referral::class, 'parent_id');

public function countSubcategories()
$count = $this->get_children()->count();

foreach ($this->get_children as $child) {
$count += $child->countSubcategories();

return $count;

In this code snippet, we have a `Referral` model with a `get_children` relationship that retrieves all the child categories of a parent category. The `countSubcategories` function recursively counts all the subcategories of a category by iterating through each child category and calling the function on them.

You can use this function in your controller or wherever you need to get the count of multilevel subcategories like this:

$category = Referral::find($categoryId);
$subcategoriesCount = $category->countSubcategories();

This will give you the total count of all subcategories under the specified category, including subcategories of subcategories and so on.

Rate this post

3 of 5 based on 4443 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us