kdes70
@kdes70
Web developer

Как в Laravel 5 получить авторизованного пользователя из роута пакета?

Привет коллеги! Помогите разобраться плиз с проблемой.
Есть некий функционал который я решил перенести в пакет-расширение.
Проблема в том что из роутов пакета я не могу получить авторизованного пользователя,
В приложении он авторизован, перехожу по роуту из пакета, auth()->user() возвращает null.
Помогите понять почему?
Вынес директорию сложил по кон нону, подключил в composer'е проекта
"repositories": [
        {
            "type": "path",
            "url": "packages/kdes70/chatter",
            "options": {
                "symlink": true
            }
        }
    ],
    "require": {
        "php": ">=7.1.3",
        "davejamesmiller/laravel-breadcrumbs": "^5.0",
        "fideloper/proxy": "~4.0",
        "laravel/framework": "5.6.*",
        "laravel/tinker": "~1.0",
        "laravelcollective/html": "^5.6",
        "predis/predis": "^1.1",
        "pusher/pusher-php-server": "~3.0",
        "spatie/laravel-fractal": "*",
        "kdes70/chatter": "*"
    },


composer.json пакета
"minimum-stability": "dev",
  "autoload": {
    "psr-4": {
      "Kdes70\\Chatter\\": "src/",
      "Kdes70\\Chatter\\ChatterController": "src/Http/Controllers/"
    },
    "files": [
      "helper/helpers.php"
    ]
  },
  "extra": {
    "laravel": {
      "providers": [
        "Kdes70\\Chatter\\ChatterServiceProvider"
      ],
      "aliases": {
        "Chatter": "Chatter\\Facades\\Chatter"
      }
    }
  }


создал сервис провайдер, где назначил свой конфиг, роутер, виды, скрипты

class ChatterServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Relation::morphMap(config('chatter.relation'));

        $this->publishes([
            $this->configPath()     => config_path('chatter.php'),
            $this->componentsPath() => base_path('resources/assets/js/components/chatter'),
        ], 'chatter');

        $this->loadRoutesFrom($this->routesPath());
        $this->loadViewsFrom($this->viewsPath(), 'chatter');
        $this->loadMigrationsFrom($this->migrationsPath());
        $this->registerBroadcast();
    }

    public function register(): void
    {
        $this->mergeConfigFrom($this->configPath(), 'chatter');
        $this->registerFacade();
        $this->registerChatter();
        $this->registerAlias();
    }

    protected function registerBroadcast(): void
    {
        Broadcast::channel(
            $this->app['config']->get('chatter.channel.chat_room') . '-{conversationId}',
            function ($user, $conversationId) {
                if ($this->app['conversation.repository']->canJoinConversation($user, $conversationId)) {
                    return $user;
                }
            }
        );
    }

    protected function registerFacade(): void
    {
        $this->app->booting(function () {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Chatter', Chatter::class);
        });
    }


    protected function registerChatter(): void
    {
        $this->app->bind('chatter', function ($app) {
            $config = $app['config'];
            $conversation = $app['conversation.repository'];
            return new ChatterService($config, $conversation);
        });
    }

    protected function registerAlias(): void
    {
        $this->app->singleton('conversation.repository', function () {
            return new ConversationRepository();
        });
        $this->app->alias('conversation.repository', ConversationRepository::class);
    }

    protected function viewsPath(): string
    {
        return __DIR__ . '/../resources/views/chatter';
    }

    protected function configPath(): string
    {
        return __DIR__ . '/config/chatter.php';
    }

    protected function componentsPath(): string
    {
        return __DIR__ . '/../resources/assets/js/components';
    }

    protected function migrationsPath(): string
    {
        return __DIR__ . '/database/migrations';
    }

    protected function routesPath(): string
    {
        return __DIR__ . '/Http/routes.php';
    }

    public function provides(): array
    {
        return [
            'conversation.repository',
        ];
    }
}

роутер
Route::group([
    'namespace'=>'Kdes70\Chatter\Http\Controllers',
    'prefix' => 'messages',
    'middleware' => ['web', 'auth'],
    ], function (){

    Route::get('/', 'ChatterController@index')->name('messages');
    Route::get('/chat/{conversation_id}', 'ChatterController@chat')->name('chat');
});
  • Вопрос задан
  • 574 просмотра
Решения вопроса 1
kdes70
@kdes70 Автор вопроса
Web developer
Суть в том что в контроллере в экшинах auth()->user срабатывает, а в конструкторе нет, Почему так?
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
erniesto77
@erniesto77
oop, rb, py, php, js
вероятнее всего вы пытаетесь получить user слишком рано

попробуйте обратиться к auth()->user позже. Если нельзя позже, то напишите

Если API, то в конструкторе
public function __construct(Request $request)
    {
        $this->middleware(['auth:api']);

        $this->user = \Auth::guard('api')->user();
    }
Ответ написан
ellrion
@ellrion
Роуты оберните в группу с мидлвар группой web.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы