how to set and get detail of user using JWT token in function __construct laravel

  jwt, laravel, php

So I have some question in here, I wanna check in every single controller in __construct function for knowing when the user access my website there still have token authorization. So I have code like this :

FieldController.php

<?php
namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use IlluminateHttpRequest;
use AppModelsField;
use Validator;
use JWTAuth;
use TymonJWTAuthExceptionsJWTException;

class FieldController extends Controller 
{
   protected $user;

   public function __construct()
   {
       $this->user = JWTAuth::parseToken()->authenticate();
   }

   public function viewManagementField()
   {
       $title = "Booking Lapangan - Management Lapangan";

       return view('admin.management-field.view', compact('title'));
   }
}

Web.php

Route::group(['prefix' => 'admin'], function () {
    Route::group(['middleware' => ['jwt.verify']], function () {
        Route::get('management-field', [FieldController::class, 'viewManagementField']);
    });
});

But I have result be like this :

enter image description here

As far as I know, the token must be set in the header when I wanna get the detail of user have been authenticated right? but how to set the token in header when I use __construct function?

Btw, when I using that request in another function and not using the __construct it was worked didn’t have any error like that, because I was set the token in my javascript before, thank you

Source: Laravel

Leave a Reply