0

I have UserController and PetController.

In my UserController, I have rewardUser() method.

in my PetController, I'm using the $user variable which indicates the current logged in user.

How I can run my rewardUser() method from my PetController?

I've been trying to user $user->rewardUser(); but for some reasons its not recognizing my method this way.

"Call to undefined method Illuminate\Database\Query\Builder::rewardUser()"
TheUnreal
  • 23,434
  • 46
  • 157
  • 277
  • http://stackoverflow.com/questions/30365169/access-controller-method-from-another-controller-in-laravel-5 – rishal Apr 24 '16 at 14:43

3 Answers3

1

The best way is to use a trait.

Create a trait file, in App\Common.php, for e.g. Then copy the rewardUser() method to the trait.

Your trait file:

namespace App\Forum;


trait Common {

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

}

Then in yourUserController.php and PetController.php, use the trait.

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

You can use the straight in as many controllers as you want and you can call the method in the straight using $this->methodName().

Very simply and effective.

Taylor
  • 2,981
  • 2
  • 29
  • 70
0

It seems like you are missing some structure concepts, but if you really need it, you may use the container to do so:

$userController = app()->make(UserController::class);
return app()->call([$userController, 'rewardUser']);
henriale
  • 1,012
  • 9
  • 21
-1

may be you should define the method rewardUser() in the User Model and import it with use App\User

Melek Yilmaz
  • 409
  • 1
  • 5
  • 16
  • Yep you are right. Defining method like that supposed to be in the Model and not in the Controller. Thanks! – TheUnreal Apr 24 '16 at 14:53