将数组转换为 Json Laravel

Convert an Array to Json Laravel

我收到这个错误

ErrorException in helpers.php line 685: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

我想转换评论实体,但我不知道那会是什么样子。

最好的选择是什么? toJson() 或 json_encode?

这是我的控制器

public function update($id, Request $request)
    {
        $trip = Trip::find($id);  
        $trip = Trip::with('comments')->where('id', $id)->first();
        $trip->fill($request->input());

        if($request->has('comments')){
            // foreach($request->comments as $comments){
            //     $comments = Comment::find($id);
            //     $comments->fill($request->input());
            //     $comments->save();

                 $commentArray=[];
        foreach($request->comments as $key=>$commentEntity) {
            // dd($commentEntity);
            // dd($request->comments);
             $comment =Comment::find($id);
            $comment->comment=$commentEntity['comment'];
            $comment->trip_id=$commentEntity['trip_id'];
            $comment->date=date('Y,m,d,G,i,s');
            $comment->user_id=$commentEntity['user_id'];
            $comment->save();
            }
        }



       if($request->files){
        foreach($request->files as $files){
            $file = File::find($id);
            $file->save();
            }       
     } 

        $trip->save();
        return response()->json($trip);

    }

我已经尝试过:

            **// $strFromArr = serialize($comment); and
            // $comment->toJson(); and this way too
            //$json = json_encode($comment);**

很简单,如果您 return 它

,它会自动将任何模型转换为 json
return $trip;

正如@omadonex 所说,在从控制器 returning 之前无需转换模型。 在 Laravel 的控制器中,您可以只 return model/collection 并且 Laravel 将负责转换。

我不认为 return $trip; 阻止了您的数据更新 - 所以我建议您进行更改并重新调试您的代码。

对于您的评论更新,将评论 ID 添加到您发送的每一行并使用此 foreach:

foreach($request->comments as $commentEntity) {
    $comment = Comment::find($commentEntity['id']);
    $comment->comment = $commentEntity['comment'];
    $comment->trip_id = $commentEntity['trip_id'];
    $comment->date = date('Y,m,d,G,i,s');
    $comment->user_id = $commentEntity['user_id'];
    $comment->save();
}