【问题标题】:Convert an Array to Json Laravel将数组转换为 Json Laravel
【发布时间】:2017-07-06 03:27:44
【问题描述】:

我收到这个错误

helpers.php 第 685 行中的错误异常: preg_replace():参数不匹配,pattern是字符串而replacement是数组

我想转换 cmets 实体,但我不知道它会是什么样子。

什么是最好的选择? toJson() 还是 json_encode?​​p>

这是我的控制器

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

【问题讨论】:

    标签: php arrays json laravel backend


    【解决方案1】:

    正如@omadonex 所说,在从控制器返回模型之前无需转换模型。 在 Laravel 的控制器中,您可以只返回模型/集合,Laravel 将负责转换。

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

    对于您的 cmets 更新,将评论 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();
    }
    

    【讨论】:

    • 那会是什么样子? $comment 与 trip 完全不同,但是 trip 有这个评论。
    • 您尝试查找带有请求 id 的评论 - 这似乎是行程的 id。尝试使用旅行模型创建评论$trip->comments()->create(['comment' => X, 'date' => Y, 'user_id' => Z])
    • 但这会创建一个新评论,对吧?或者它也适用于更新?
    • 它只会创建,您需要创建、更新还是两者兼而有之?
    • 实际上我需要两者,并且以相同的形式,我不知道如何实现,但那是为了以后,我试图修复这个错误,不要将数据保存在数据库中。如果您看到它,它是一个更新功能。如何在更新中应用您给我的解决方案?
    【解决方案2】:

    很简单,如果你返回它,它会自动将任何模型转换为 json

    return $trip;
    

    【讨论】:

    • 已经试过了,不再显示错误,但不更新db中的数据。
    猜你喜欢
    • 2016-04-01
    • 2020-04-16
    • 2017-11-29
    • 2018-02-26
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    相关资源
    最近更新 更多