Laravel Json资源:array_merge_recursive():参数2不是数组

时间:2018-08-27 18:30:30

标签: laravel laravel-5 laravel-5.6 laravel-response laravel-resource

我有一个JsonResource中的一个Post应该返回一个帖子。但是在加入其他数据后,我得到了这个错误:array_merge_recursive(): Argument #2 is not an array

不起作用

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($slug)
{
    // $post = Post::findOrFail($id);
    $post = Post::where('slug', $slug)->first();
    // return single post as resource
    return new PostResource($post);
}

当我直接返回$posts时,我得到了一个json,几乎可以了。但是它不包含联接数据comment

这里是class Post extends JsonResource

public function toArray($request)
{
    // return parent::toArray($request);
    $img = '.'.pathinfo('storage/'.$this->image, PATHINFO_EXTENSION);
    $imgName = str_replace($img,'', $this->image);
    $img = $imgName.'-cropped'.$img;

    return [   
        'id' => $this->id,
        'title' => $this->title,
        'body' => $this->body,
        'excerpt' => $this->excerpt,
        'image' => asset('/storage/' . $this->image),
        'image_small' => asset('storage/' . $img),
        'author_id' => $this->author_id,
        'category_id' => $this->category_id,
        'seo_title' => $this->seo_title,
        'slug' => $this->slug,
        'meta_description' => $this->meta_description,
        'meta_keywords' => $this->meta_keywords,
        'status' => $this->status,
        'featured' => $this->featured,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'user' => User::find($this->author_id),
        'commentCount' => $this->comment->where(['status' => 1, 'id_post' => $this->id])->count(),
    ];
}

// **Big mistake below here**:
public function with($request)
{
    // return [
    //     'version' => '1.0.0',
    // ];
}

型号:

class Post extends Model
{
    public $primary_key = 'id';
    public $foreign_key = 'id_post';

    public function user()
    {
        return $this->belongsTo('App\User', 'id_author', 'id');
    }

    public function comment()
    {
        return $this->belongsTo('App\Comment', 'id', 'id_post');
    }
}

为什么会收到有关array_merge_recursive()的警告?

1 个答案:

答案 0 :(得分:2)

我不会在您的代码中重现问题,但是-您确定已包含所有内容吗?看着https://laravel.com/docs/5.6/eloquent-resources#writing-resources,可以这样定义其他数据:

/**
 * Get additional data that should be returned with the resource array.
 *
 * @param \Illuminate\Http\Request  $request
 * @return array
 */
public function with($request)
{
    return [
        'meta' => [
            'key' => 'value',
        ],
    ];
}

因此,当我通过以下方法向此Post资源类添加内容时,便能够重现该问题:

public function with($request)
{
    return 'test';
}

如您所见,它只返回字符串而不是数组,所以我得到的错误与您相同。

但是当我根本没有实现此方法或仅返回数组时,一切都很好。

因此,总结一下-确保没有定义with方法,该方法返回的不是数组。