Trying to access array offset on value of type null in file

huangapple go评论71阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2023年2月24日 12:06:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定