我的控制器代码:
public static async Task AuthenticationFailed(this AuthenticationFailedContext context)
{
ILoggerFactory loggerFactory = context.HttpContext.RequestServices.GetService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger(nameof(JwtBearerExtensions));
string refreshToken = context.HttpContext.Request.Cookies[Defaults.RefreshTokenCookie];
if (string.IsNullOrEmpty(refreshToken))
{
logger.LogWarning("No refresh token supplied with invalid JWT, Cookies are {0}", string.Join(", ", context.HttpContext.Request.Cookies.Keys));
return;
}
logger.LogInformation("Processing refresh token '{0}'.", refreshToken);
IConfiguration configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
IUserService userService = context.HttpContext.RequestServices.GetService<IUserService>();
ITokenHandler handler = context.HttpContext.RequestServices.GetService<ITokenHandler>();
long? userId = await handler.ValidateRefreshToken(refreshToken);
if (userId.HasValue)
{
User user = await userService.GetUserAsync(userId.Value);
refreshToken = await handler.GenerateRefreshToken(userId.Value);
string jwtToken = BuildJwtToken(user, configuration);
context.HttpContext.Response.AddBearerAuthorization(jwtToken);
context.HttpContext.Response.AddRefreshTokenCookie(refreshToken);
context.Principal = new ClaimsPrincipal(BuildClaimsIdentity(user));
context.Success();
}
}
存在关联的我的小组模型
Response
我的请求参数:
public function addGroup(Request $request)
{
$validator = UserValidations::validateGroups($request->all());
if($validator->fails()) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
}
try {
$request->request->add(['created_by' => Auth::user()->id]);
$group = $this->group->create($request->only($this->group->getModel()->fillable));
if(!empty($request->get('group_members')))
{
$groupMembers = Group::where('id', $group->id);
$groupMembers->users()->attach($request->get('group_members'));
}
return response(['status' => true, 'message' => 'Group added', 'data' => $group], 500);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $ex->getMessage()], 500);
}
}
我想用组成员(用户)分配组名并创建组名,但是我遇到了public function users()
{
return $this->belongsToMany('App\Models\Users\User', 'group_members');
}
我在哪里做错了? 非常感谢您的帮助!
答案 0 :(得分:2)
您必须以这种方式获取组:
$groupMembers = Group::where('id', $group->id)->first();
要能够将Users
附加到Group
,首先需要使用first()
获取实例。您无法在attach()
上致电Query\Builder