Reputation: 2469
I am using jwt for CRUD in my controller, I have products and want to save the $user_id in database :
public function store(Request $request)
{
$this->user = JWTAuth::parseToken()->authenticate();
$this->validate($request, [
'name' => 'required',
'price' => 'required|integer',
'quantity' => 'required|integer'
]);
$product = new Product();
$product->name = $request->name;
$product->price = $request->price;
$product->quantity = $request->quantity;
$product->user_id = $this->user;
$product->save;
if ($product)
return response()->json([
'success' => true,
'product' => $product
]);
else
return response()->json([
'success' => false,
'message' => 'Sorry, product could not be added'
], 500);
}
It works fine but i used :
$this->user = JWTAuth::parseToken()->authenticate();
In some of my methods in controller , so I want to prevent repeating that and write it in construct of my controller, but when I run:
php artisan route:list
It shows this error:
The token could not be parsed from the request
Upvotes: 2
Views: 5989
Reputation: 6133
The version of JWTAuth that you're using doesn't integrate itself nicely with Laravel and should probably be avoided for that reason.
That aside, the reason you're getting this is that your requests don't exist properly when the constructor is called. Instead, open up you base controller (typically app/Http/Controllers/Controller
) and add the following method.
protected function user() {
return JWTAuth::parseToken()->authenticate();
}
That way whenever you want the user, you can just do $this->user()
.
Upvotes: 2