英文:
Trying to access array offset on value of type null in file
问题
以下是代码部分的中文翻译:
public function create(Request $request){
$user = $request->input('user');
$course = $request->input('course');
$order = Order::create([
'user_id' => $user['id'],
'course_id' => $course['id']
]);
return response()->json($order);
}
希望这对您有帮助。如果您需要进一步的解释或帮助,请随时提问。
英文:
ErrorException: Trying to access array offset on value of type null in file.
sorry if i dont't understand that much, I just started learning Laravel, can someone please help me, I want to show the order data with the user id and course id. My code is like this
public function create(Request $request){
$user = $request->input('user');
$course = $request->input('course');
$order = Order::create([
'user_id' => $user['id'],
'course_id' => $course['id']
]);
return response()->json($order);
}
and got an error in post man like this
ErrorException: Trying to access array offset on value of type null in file
答案1
得分: 0
你正在首先尝试将字符串用作数组,而$user
或$course
的值为null
,表示请求中未发送任何值。
在尝试将数据保存到数据库表之前,应添加某种验证。
public function create(Request $request){
$user = $request->input('user');
$course = $request->input('course');
if(!$user || !$course){
return response()->json(['error' => true], 422); //在这里执行某种验证响应或使用Laravel的验证方法
}
$order = Order::create([
'user_id' => $user,
'course_id' => $course
]);
return response()->json($order);
}
英文:
You are trying to use the string as an array first, and the value of $user
or $course
is coming in as null
meaning no value is being sent in the request.
You should add some sort of validation first before you try to save the data to the database table.
public function create(Request $request){
$user = $request->input('user');
$course = $request->input('course');
if(!$user || !$course){
return response()->json(['error' => true], 422); //do some validation response error or use laravels validation methods
}
$order = Order::create([
'user_id' => $user,
'course_id' => $course
]);
return response()->json($order);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论