DomainFlag DomainFlag - 3 months ago 47
PHP Question

Laravel, Method [...] does not exist

I have the controller:

class Comments extends Controller
{
public function GenerateComments($id)
{
$theme = DB::table('New_Themes')
->where('id', $id)
->get();

$Comments = NewTheme_Comment::where('id_theme', $id)->get();

$array = $this->tree($Comments);

function tree($Comments, $parent_id = 0, $level=0, $c=0)
{
global $var;
global $array;
global $m;

foreach($Comments as $Comment)
{
if ($Comment['parent_id'] == $parent_id) {

$m++;

$array[$m][0]=$Comment['id'];

If ($level > $var) {$var++; $array[$m][1]=0;} else {

if ($c < 0) $array[$m][1]=$var-$level+1; else {$c--; $array[$m][1]=0;};
$var=$level;
};

tree($Comments, $Comment['id'], $level+1,$c);
}
};

return $this->$array;
};

return view('comments', ['Themes'=> $theme, 'Comments'=> $Comments, 'Array' => $array]);
}


The problem is


Method [tree] does not exist.


but I don't understand why it appears, if I am calling a function within a function (like that below)

$array = $this->tree($Comments);

function tree($Comments, $parent_id = 0, $level=0, $c=0)
{
return $this->$array;
}


Are there any ideas why this isn't working?

Answer

You are calling your function tree with $this which means PHP will look tree as a method inside Comments class instead of your GenerateComments method.

Change

$array = $this->tree($Comments);

To this

$array = tree($Comments);

Note: You are also defining your function after you are calling it. PHP will look tree as it is in the namespace so it'll either won't work. Instead just define your function before you call it. Like so

function tree($Comments, $parent_id = 0, $level = 0, $c = 0) {
    // ...
}

$array = tree($Comments);

It is also not recommended to define your function inside of a function. Instead doing that, just make your tree function a method inside your controller and use that instead. Like so

class Comments extends Controller 
{
    public function GenerateComments() 
    {
        // ...
        $array = $this->tree($comments);
    }

    public function tree($tree) 
    {
        // ...
    }
}
Comments