Hasith's avatar
Level 1

JetStream $request->user() Null.

I'm trying to access backend route for get data from a external API inside a Livewire component method. But inside the Laravel Controller method i can not access $request->user() or auth()->user() if i already logged in. Thus the route is a public one both logged in and not logged in users can access that. the difference is auth user have different params and guest users has different params but same endpoint.

   public function loadPublications($params)
    {
        $page = $params['page'] ?? $this->currentPage;
        $language = $params['language'] ?? $this->selectedLanguage;
        $this->selectedLanguage = $language;
        $this->currentPage = $page;

        $response = Http::get(route('publications.get'), ['page' =>$this->currentPage, 'language' => $this->selectedLanguage]);

        if ($response->successful()) {
            $this->publications = $response->json();
        } else {
            // Handle the error
            $this->publications = [];
        }

      $this->dispatch('publications-loaded', ['pagination' => isset($this->publications['pagination']) ? 
      $this- >publications['pagination'] : null]);
    }
Route::get('/publications/get', [LarcierController::class, 'getPublications'])->name('publications.get');

public function getPublications(Request $request)
    {
        Log::info('Get Publications');
        $user = $request->user();
        $user2 = auth()->user();
}
0 likes
3 replies
Snapey's avatar

Never call your own same site as an api. Apart from being totally pointless, making an http call is very slow (it must start a copy of the framework), it is also not sending the cookie needed for user identification.

Hasith's avatar
Level 1

@Snapey I'm new to Livewire. What is the best way to call that External API and get data from it? I have to use that in multiple places BTW.

what about something like this inside the livewire method?

app(ExampleService::class)->getAPIdata();
Snapey's avatar
Snapey
Best Answer
Level 122

@Hasith Livewire is just php code like any other class. How do you get data from another class? You instantiate it and call its methods.

The only other consideration is if the code you need to execute is in a controller. In which case, I would move the relevant code to an action class or service provider and then call it from both the livewire component and the original controller

1 like

Please or to participate in this conversation.