Framework: [>=5.4] App makeWith() does not allow passing constructor parameters

Created on 12 Sep 2017  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.4 and 5.5
  • PHP Version: 7.1.6

Description

Laravel fails to resolve the dependencies of a class when instantiating with parameters.

Does the current implementation only support having those parameters passed to the closure when binding an interface or alias in e.g. a service provider or should the framework pass them to the constructor of the class and is this a bug? I remember there being a paramount distinction in the use of this method.

Steps To Reproduce

  1. Create a new project using laravel new directory
  2. Create a new class with constructor parameters (type hint optional):
<?php

namespace App;

class ApiService
{
    /**
     * @var string
     */
    public $clientId;

    /**
     * @param string $clientId
     */
    public function __construct(string $clientId)
    {
        $this->clientId = $clientId;
    }
}
  1. Somewhere in your code, e.g. the boot method in AppServiceProvider (to test in the CLI):
public function boot()
{
    app(ApiService::class, ['id']);

    // or

    app()->makeWith(ApiService::class, ['id']);
}

References

Most helpful comment

This is intentional, you need to pass the parameter name:

app()->makeWith(ApiService::class, ['clientId' => 'id']);

All 2 comments

This is intentional, you need to pass the parameter name:

app()->makeWith(ApiService::class, ['clientId' => 'id']);

That seems odd, but ok :p If a parameter is missing, does the container auto-resolve it if type-hinted?

Was this page helpful?
0 / 5 - 0 ratings