codenex's avatar

IOC from Controller

How do I get access to the IOC container from within a controller?

I have moved some logic out of the routes file and am now using a controller. I could use the IOC from the $app variable in route without an issue

$app->get('/', function () use ($app) {
    return $app->version();
});

However if I change this to send to a controller

$app->get('/', 'HomeController@index');
// HomeController
class HomeController extends Controller
{
    public function index()
    {
        return $app->version();
    }
}

Then I get the following error:

Undefined variable: app
0 likes
6 replies
isaackearl's avatar

I don't have a way to test it at the moment but I think you just need to typehint.

// HomeController
class HomeController extends Controller
{
    public function index(App $app)
    {
        return $app->version();
    }
}

Could be wrong but I'm pretty sure your just missing the tyehinting. You could also use App as a facade I'm pretty sure in your controller

// HomeController
class HomeController extends Controller
{
    public function index()
    {
        return App::version();
    }
}
codenex's avatar

Just type hinting it didn't work.

Class App\Http\Controllers\App does not exist

Even changing it to \App or importing it at the top of the controller gives the following error:

Class App does not exist
EliasSoares's avatar

Try import the facade:

use \App;

Or simply do

\App::version ()
SaeedPrez's avatar
Level 50

Simply use the helper..

return app()->version();
codenex's avatar

@SaeedPrez That worked, thanks! I'm a little curious where in the docs this is explained. If I have a package registered in the IOC container and I want to utilize a function within it, this seems like it would be important to know.

Perhaps in the bigger picture you are really using it within your own apps custom classes which I understand. However if I'm testing functionality of a package (or developing) one I'm usually testing within the routes file or the controller.

Please or to participate in this conversation.