I have a middleware that authenticates a JWT user using tymon/jwt-auth package:
public function handle($request, \Closure $next)
{
if (! $token = $this->auth->setRequest($request)->getToken()) {
return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
}
try {
$user = $this->auth->authenticate($token);
} catch (TokenExpiredException $e) {
return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
} catch (JWTException $e) {
return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
}
if (! $user) {
return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
}
$this->events->fire('tymon.jwt.valid', $user);
return $next($request);
}
Then I have a controller and I want to pass the user from the middleware to the controller.
So I did on the controller:
public function __construct()
{
$this->user = \Auth::user();
}
The problem is that $this->user
is null
, but when I do this on a method of the controller, it's not null.
So:
public function __construct()
{
$this->user = \Auth::user();
}
public function index()
{
var_dump($this->user); // null
var_dump(\Auth::user()); // OK, not null
}
So the issue is that __construct
is running before the middleware. How can I change that, or do you have another solution?
Update: I'm using dingo/api for routing, maybe it's an error on their side?
Laravel middleware provide us a convenient mechanism for filtering any HTTP requests entering of our applications. So now here i will show you a example by using constructor for adding a middleware for each method as like index, create, store, edit, delete, show and also update of controller.
A: In Laravel, you can add a Controller by using the Artisan command: This will create the controller in the app/Http/Controllers directory. Share your opinion in the comment section. COMMENT NOW Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways.
This means that in the request lifecycle, the controller constructor has to be before the middlewares. This luckily has been solved and if you use a callback for middleware dependent logic in the constructor, you will avoid this problem.
The easiest way to define the middleware is in the constructor of the controller. Remember to define the namespace of the middleware in the controller as well. See the following code for defining the middleware in the constructor:
You should use the middleware(s) in the routes
Route::middleware('jwt.auth')->group(function() {
// your routes
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With