0

I am trying to call a static function from the controller which is already written and I just want to reuse that function.

Controller:

public static function getProjectName($project_id){
     $project_obj = new Project();
     $project = $project_obj->find($project_id); 
     return $project->project_name;
}

This code is working fine if I call this static function in the same or another controller. But I'm trying to call it from routes.php something like below:

routes.php

Route::get('/get-project-name/{project_id}', 'ProjectController@getProjectName');

I am calling the same function using above code in routes.php but every time I'm getting 405 error that is method not allowed.
How can I call this static function from route in Laravel

1 Answer 1

4

It is not a good idea to use controller methods to get a database value.

Instead, use its model and call the model method anytime you need.

class Project extends Model 
{
    public function getProjectName($id)
    {
        $project = $this->find($id);
        return $project ? $project->name : null;
    } 

}

And if you need to call it statically

class Project extends Model 
{
    public static function getProjectName($id)
    {
        $project = self::find($id);
        return $project ? $project->name : null;
    } 

}

if you need to use it in the routes

Route::get('/get-project-name/{id}', function ($id) {
    return Project::getProjectName($id);
});
Sign up to request clarification or add additional context in comments.

2 Comments

@Onkar why do you want to call it in the route?
@Onkar Updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.