[英]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调用它,如下所示:
routes.php 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. 我在routes.php中使用上述代码调用了相同的函数,但是每次遇到405错误,这是不允许的方法。
How can I call this static function from route in Laravel 如何从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. 而是使用其模型并在需要时随时调用model方法。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.