S.M_Emamian S.M_Emamian - 1 month ago 16
PHP Question

recursive function in model doesnt return anything - laravel

I made a function inside

category
model :

public function getSecondCategoryByID($category_id = 0,$id = 0)
{

$category = $this->where('id','=',$category_id)->first();

if($category->parent_cat_id == 1)
{

$mcategory = $this->where('id','=',$id)->first();


echo 'Inside Model '.$mcategory->id;
return $mcategory->id;


}else{
$this->getSecondCategoryByID($category->parent_cat_id,$category->id);
}

}


at a function of controller I called this function :

$category = new Category;

$secondCategoryID = $category->getSecondCategoryByID($category_brand->category_id,0);

echo 'After Model '.$secondCategoryID ;
return ;


when I call my function of controller I got this message on page :

Inside Model 3After Model //it should be Inside Model 3After Model '3'


I think my model doesn't return anything ! because after
after model
is nothing !!!!!

Answer

When doing recursion you need to return the recursive call also, here shown by changing the else block statement.

else
{
    return $this->getSecondCategoryByID($category->parent_cat_id,$category->id);
}