1

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 !!!!!

S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

1 Answers1

3

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);
}
mrhn
  • 17,961
  • 4
  • 27
  • 46
  • What's great about this answer is that it works for ajax calls to Laravel controllers. Before trying this, in my controller, I was calling my recursive method and not returning anything, which returned a blank string to ajax. – Kevin Tesar Jul 02 '21 at 21:52