Отсутствует аргумент 1 для Illuminate \ Support \ Manager :: createDriver ()

Я просмотрел все сообщения, связанные с этой ошибкой в ​​Laravel:

Отсутствует аргумент 1 для Illuminate Support Manager - createDriver ()

2-я ссылка

3-я ссылка

Ни один из них не решил мою проблему: я использую Laravel Lumen версии 5.4 и пакет Dingo API.

Я хочу получить доступ к аутентифицированному пользователю во входящем запросе:

 $request->user(); //returns an instance of the authenticated user

Однако это вызовет у меня сообщение об ошибке:

Отсутствует аргумент 1 для Illuminate \ Support \ Manager :: createDriver (), который был вызван в /var/www/html/myApp/vendor/illuminate/support/Manager.php в строке 88 и определен ",

Я знаю, что для получения аутентифицированного пользователя вам необходимо предоставить промежуточное ПО для аутентификации внутри маршрутизации:

  $api->get('register/{accountId}', ['middleware' => 'auth', 'App\Http\Controllers\Api\V1\RegisterController@registerAction']);

Но добавление промежуточного программного обеспечения Auth внутри моего маршрута на самом деле не достигнет конечной точки контроллера и вызовет ту же ошибку, которую вы можете увидеть выше.

У меня AuthServiceProvider зарегистрирован в моем bootstrap / app.php:

 $app->register(App\Providers\AuthServiceProvider::class);

А это класс AuthServiceProvider:

 <?php

 namespace App\Providers;

 use App\Models\Account;
 use Illuminate\Support\ServiceProvider;

 class AuthServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   *
   * @return void
   */
   public function register() {
   }

  /**
   * Boot the authentication services for the application.
   *
   * @return void
   */
   public function boot() {
    // Here you may define how you wish users to be authenticated for your Lumen
    // application. The callback which receives the incoming request instance
    // should return either a User instance or null. You're free to obtain
    // the User instance via an API token or any other method necessary.

    $this->app['auth']->viaRequest('api', function ($request) {

        if ($request->input('api_token')) {
            return Account::where('api_token', $request->input('api_token'))->first();
        }
    });
   }
  }

Вот что у меня в config / auth.php:

  <?php

  return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
 ],

];

Я сам попытался отладить проблему и обнаружил, что именно здесь она ломается в Laravel:

/**
 * Create a new driver instance.
 *
 * @param  string  $driver
 * @return mixed
 *
 * @throws \InvalidArgumentException
 */
protected function createDriver($driver)
{
    // We'll check to see if a creator method exists for the given driver. If not we
    // will check for a custom driver creator, which allows developers to create
    // drivers using their own customized driver creator Closure to create it.
    if (isset($this->customCreators[$driver])) {
        return $this->callCustomCreator($driver);
    } else {
        $method = 'create'.Str::studly($driver).'Driver';

        if (method_exists($this, $method)) {
            return $this->$method();
        }
    }
    throw new InvalidArgumentException("Driver [$driver] not supported.");
}

Я вижу в stackTrace, что он передает драйвер NULL внутри метода createDriver (), который вызывает мою ошибку. Интересно, а не простая ли конфигурация, которую я должен добавить в свой файл .env.

Я начинаю с Laravel Lumen, это отличный инструмент для создания API, и я не виню сам инструмент (я потратил много времени на чтение красивой документации), я почти уверен, что пропустил что-то очень простое, если кто-то может помочь мне в этом, я буду очень рад.


person Nizar B.    schedule 14.04.2017    source источник
comment
Вы раскомментировали вызов $app->routeMiddleware() в bootstrap/app.php.   -  person Pankit Gami    schedule 14.04.2017
comment
@PankitGami Да, у меня есть в начальной загрузке ›app.php эта строка: $ app-› routeMiddleware (['auth' = ›App \ Http \ Middleware \ Authenticate :: class,]);   -  person Nizar B.    schedule 14.04.2017
comment
Это прокомментировано или раскомментировано?   -  person Pankit Gami    schedule 14.04.2017
comment
@PankitGami Он раскомментирован, вызов routeMiddleware доступен в бутстрапе.   -  person Nizar B.    schedule 14.04.2017


Ответы (1)


Вы используете Laravel Scoutпоисковый драйвер Algolia)?

Я столкнулся с ошибками, которые вы видели при запуске моих семян базы данных. В конце концов, я понял, что мой усталый ум забыл определить правильные переменные env в моем файле .env, как показано ниже:

SCOUT_DRIVER=algolia
ALGOLIA_APP_ID=yourAlgoliaAppId
ALGOLIA_SECRET=yourAlgoliaSecret

Если вы не опубликовали файл конфигурации scout, сделайте это с помощью следующей команды:

поставщик php artisan: publish --provider = "Laravel \ Scout \ ScoutServiceProvider"

Убедитесь, что вы поместили Laravel \ Scout \ ScoutServiceProvider :: class в массив поставщиков в config / app.php, прежде чем запускать указанную выше команду.

После того, как я опубликовал файл конфигурации (по умолчанию названный config / scout.php), я использовал переменные env, как показано ниже:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Search Engine
    |--------------------------------------------------------------------------
    |
    | This option controls the default search connection that gets used while
    | using Laravel Scout. This connection is used when syncing all models
    | to the search service. You should adjust this based on your needs.
    |
    | Supported: "algolia", "elasticsearch", "null"
    |
    */

    'driver' => env('SCOUT_DRIVER'),

    /*
    |--------------------------------------------------------------------------
    | Index Prefix
    |--------------------------------------------------------------------------
    |
    | Here you may specify a prefix that will be applied to all search index
    | names used by Scout. This prefix may be useful if you have multiple
    | "tenants" or applications sharing the same search infrastructure.
    |
    */

    'prefix' => env('SCOUT_PREFIX', ''),

    /*
    |--------------------------------------------------------------------------
    | Queue Data Syncing
    |--------------------------------------------------------------------------
    |
    | This option allows you to control if the operations that sync your data
    | with your search engines are queued. When this is set to "true" then
    | all automatic data syncing will get queued for better performance.
    |
    */

    'queue' => false,

    /*
    |--------------------------------------------------------------------------
    | Algolia Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your Algolia settings. Algolia is a cloud hosted
    | search engine which works great with Scout out of the box. Just plug
    | in your application ID and admin API key to get started searching.
    |
    */

    'algolia' => [
        'id' => env('ALGOLIA_APP_ID'),
        'secret' => env('ALGOLIA_SECRET'),
    ],

];

Как только я сделал все вышеперечисленное, ошибки исчезли. Этот ответ может не напрямую относиться к вашей конкретной проблеме, но, возможно, он может напомнить вам или помочь в процессе устранения неполадок.

person Rob    schedule 30.04.2017