Jrb
Jrb

Reputation: 461

Why Auth::user() return null in routes of a custom Service Provider?

I'm making a new Service called Factures in App\Services\Factures. I created the \App\Services\Factures\FacturesServiceProvider:

public function register() {
    $this->app->bind('factures', function ($app) {
        return new Facture;
    });
}

public function boot() {
    // laod Routes
    $this->loadRoutesFrom(__DIR__ .'/Http/routes.php');

    // load Views
    $this->loadViewsFrom(__DIR__ . '/views', 'factures');
}

I registered my provider everything works fine expect the Auth::user() in returns me  null in the views and the routes.php.

How can I get access to the Auth() in custom service?

Upvotes: 0

Views: 535

Answers (1)

Jrb
Jrb

Reputation: 461

This post resolved my problem: User Auth not persisting within Laravel package

I figure out that Laravel  apply to the default routes/web.php file a middleware called 'web' And doesn't apply this group to external package routes loaded via service provider's.

So my routes in the custom file should be in web middleware:

Route::group(['middleware' => ['web']], function () {
    Route::get('testing-services', function(){
        dd(Auth::user());
        // output is valid
    });
});

Upvotes: 1

Related Questions