2016-04-24 164 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']); 
相關問題