Passing dependency parameters to App::make() or App::makeWith() in Laravel

20,232

Solution 1

You can see detailed documentation here: https://laravel.com/docs/5.6/container#the-make-method

It's done like this:

$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);

Or use the app() helper

$api = app()->makeWith(HelpSpot\API::class, ['id' => 1]);

It is essential to set the array key as the argument variable name, otherwise it will be ignored. So if your code is expecting a variable called $modelData, the array key needs to be 'modelData'.

$api = app()->makeWith(HelpSpot\API::class, ['modelData' => $modelData]);

Note: if you're using it for mocking, makeWith does not return Mockery instance.

Solution 2

You can also do it this way:

$this->app->make(SomeClass::class, ["foo" => 'bar']);
Share:
20,232
jd182
Author by

jd182

Updated on January 14, 2020

Comments

  • jd182
    jd182 over 4 years

    I have a class that uses a dependency. I need to be able to dynamically set parameters on the dependency from the controller:

    $objDependency = new MyDependency();
    $objDependency->setSomething($something);
    $objDependency->setSomethingElse($somethingElse);
    
    $objMyClass = new MyClass($objDependency);
    

    How do I achieve this through the Service Container in Laravel? This is what I've tried but this seems wrong to me. In my AppServiceProvider:

    $this->app->bind('MyClass', function($app,$parameters){
    
        $objDependency = new MyDependency();
        $objDependency->setSomething($parameters['something']);
        $objDependency->setSomethingElse($parameters['somethingElse']);
    
        return new MyClass($objDependency);
    }
    

    And then in the controller i'd use this like:

    $objMyClass = App:make('MyClass', [
        'something'     => $something, 
        'somethingElse' => $somethingElse
    ]);
    

    Is this correct? Is there a better way I can do this?

    Thanks