简体   繁体   中英

How to call static function from routes.php in Laravel

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

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM