Reputation: 285
I am trying to save my data against logged in user id. But I am unable to do it. I am testing my api using Postman and using JWT auth. When I am logged in I get a token. I can save data against user_id
with that token. But I don't want to pass that token on every request.
What I am trying here is to save user_id
like this:
auth()->guard('api')->user();
My whole controller method:
$business = new Business();
$business->business_name = Input::get('business_name');
$business->business_url = Input::get('business_url');
$business->user_id = auth()->guard('api')->user();
$business->save();
$resultArray = ['status' => 1,
'message' => 'Business added!',
'dataArray' => $business
];
When i go with this error is
Integrity constraint violation: 1048 Column 'user_id' cannot be null
When I log in I get a response like following:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNTIzOTYxNDEwLCJleHAiOjE1MjM5OTc0MTAsIm5iZiI6MTUyMzk2MTQxMCwianRpIjoiVWppUVVXTENWNjQ4WTJWNyIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.rIjmaEA1HdG64uolyKO9gVX6mqiQ8PN-a2YGO2-Palo",
"currentUser": {
"id": 1,
"name": "Shahzad Hussain",
"email": "[email protected]",
"created_at": "2018-04-17 05:55:55",
"updated_at": "2018-04-17 05:55:55"
}
}
I need your help and it will be highly appreciated!
Upvotes: 2
Views: 1868
Reputation: 1651
change
auth()->guard('api')->user();
to
\Auth::user()->id
or
public function __construct(Guard $auth)
{
$this->currentUser = $auth->user();
}
$business->user_id = $this->currentUser->id;
or
auth()->user()->id
Upvotes: 1