Home » Php » php – Call to undefined function : Laravel 5.1

php – Call to undefined function : Laravel 5.1

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a private function as written below in the Controller.

private function GetProjects($ProjectStatus) {
    return \App\Models\Project\Project_Model
            ::where('ProjectStatusID', $ProjectStatus)
            ->where('WhoCreatedTheProject', auth()->user()->UserID)->get();
}

Below is the action method that is using this private function.

public function ClientCancelledProjects() {
    $ProjectStatus = \App\Enumeration\Project\ProjectStatus::Cancelled;         
    $MyProjects = GetProjects($ProjectStatus);
    return view("Project.Client.MyProject", array("Projects" => $MyProjects));
}

Below is the Error coming when running the controller.

Call to undefined function App\Http\Controllers\Project\GetProjects()

Somebody knows why this is happening ? I am trying to reuse some lines of code as they are written many times in the Controller.

How to&Answers:

To access functions in a controller from a function in the same controller, use self:::

public function ClientCancelledProjects() {
    $ProjectStatus = \App\Enumeration\Project\ProjectStatus::Cancelled;         
    $MyProjects = self::GetProjects($ProjectStatus);
    return view("Project.Client.MyProject", array("Projects" => $MyProjects));
}

Note: Self:: (uppercase) will work depending on the version of php installed, but for older versions, self:: is preferred.

Please check this link for more info: PHP – Self vs $this

Answer:

Functions inside of a class are not global functions, and cannot be called that way. You need to use $this->GetProjects() instead.