在尝试发出发布请求时,它会通过我的控制器不断提供failed
。我正在尝试上传文件并将与用户关联的文件名存储到我的数据库中。我不确定自己在这里做错了什么,我已经尝试了多种方法来解决此问题,但由于碰壁而无济于事。我相信这可能是我在控制器中编写代码的方式,但是我不太确定。
我在日志中遇到的错误是Call to a member function photos() on null
,这意味着
auth()->user()
未检测到经过身份验证的用户,这就引出了一个问题-如何?我使用正确的凭据登录,没有任何问题。为什么无法在单独的控制器中进行验证?
我在做什么错,我该如何解决?
注意:我的React.js和Laravel代码库是分开的。
这是我的反应形式:
handleSubmit(e) {
e.preventDefault();
console.log("here in submitHandler()");
let access_token = Cookies.get("access_token").slice(13, -8);
const headers = {
Authorization: `Bearer ${access_token}`
}
console.log(this.state.file_path);
axios.post('http://myendpoint/api/auth/dashboard', this.state.file_path, {headers})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
})
};
这是我的FileUploadController.php
:
public function uploadTest(Request $request) {
if(auth()->user()) {
auth()->user()->photos()->create([
'file_path' => $request->file('fileToUpload')->getClientOriginalExtension()
]);
return response()->json($request->session()->get("user"));
}
return "failed";
}
这是我的用户模型:
public function photos() {
return $this->hasMany(Photo::class);
}
这是我的照片模特:
public function user() {
return $this->belongsTo(User::class);
}
这是创建用户并登录(AuthController.php
)的身份验证:
public function signup(Request $request) {
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function login(Request $request) {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$request->session()->put("user", $user);
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
$user
]);
}