2016-04-24 118 views
0

我有UserControllerPetControllerLaravel - 在一个控制器中运行另一个控制器的方法

在我的UserController,我有rewardUser()方法。

在我的PetController,我使用$user变量,它指示当前登录的用户。

如何从我的PetController运行我的rewardUser()方法?

我一直在尝试用户$user->rewardUser();,但由于某些原因,它不能识别我的方法。

"Call to undefined method Illuminate\Database\Query\Builder::rewardUser()" 
+0

http://stackoverflow.com/questions/30365169/access-控制器方法从另一个控制器在laravel 5 – rishal

回答

-1

可能是你应该在用户模型中定义的方法rewardUser()use App\User

+0

是的,你说得对。定义类似于应该在模型中而不是在控制器中的方法。谢谢! – TheUnreal

1

导入它的最好方法是使用一个特点。

创建一个特征文件,在App\Common.php中,例如,然后将rewardUser()方法复制到特征。

你的特质文件:

namespace App\Forum; 


trait Common { 

    public function rewardUser() { 
     // Your code here... 
    } 

} 

然后在你的UserController.phpPetController.phpuse性状。

// UserController and PetController.php 

namespace App\Http\Controllers 

use App\Common; // <- Your trait 


class UserController extends Controller { 

use Common // <- Your trait 

    public function doSomething() { 

     // Call the method from both your controllers now. 
     $this-rewardUser(); 
    } 
} 

您可以使用尽可能多的控制器直,只要你想,你可以调用使用$this->methodName()在直的方法。

非常简单而有效。

0

好像你缺少某些结构的概念,但如果你真的需要它,你可以使用容器可以这样做:

$userController = app()->make(UserController::class); 
return app()->call([$userController, 'rewardUser']); 
相关问题