我正在尝试根据登录的用户ID保存我的数据。但我无法做到。我正在使用Postman测试我的api并使用JWT auth。当我登录时,我得到一个令牌。我可以使用该令牌针对user_id
保存数据。但我不想在每个请求上传递该令牌。
我在这里尝试的是保存user_id
,如下所示:
auth()->guard('api')->user();
我的整个控制器方法:
$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
];
当我使用此错误时
完整性约束违规:1048列'user_id'不能为空
当我登录时,我收到如下回复:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNTIzOTYxNDEwLCJleHAiOjE1MjM5OTc0MTAsIm5iZiI6MTUyMzk2MTQxMCwianRpIjoiVWppUVVXTENWNjQ4WTJWNyIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.rIjmaEA1HdG64uolyKO9gVX6mqiQ8PN-a2YGO2-Palo",
"currentUser": {
"id": 1,
"name": "Shahzad Hussain",
"email": "shahzadshahg@hotmail.com",
"created_at": "2018-04-17 05:55:55",
"updated_at": "2018-04-17 05:55:55"
}
}
我需要你的帮助,我们将非常感激!
答案 0 :(得分:1)
变化
auth()->guard('api')->user();
到
\Auth::user()->id
或
public function __construct(Guard $auth)
{
$this->currentUser = $auth->user();
}
$business->user_id = $this->currentUser->id;
或
auth()->user()->id