lundi 27 août 2018

Laravel JsonResource: array_merge_recursive(): Argument #2 is not an array

I have a JsonResource of Post that should return a single post. But after joining some other data I get this error: array_merge_recursive(): Argument #2 is not an array.

This does not work:

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

When I directly return $posts, I get a json back, almost fine. But it doesnt contain the joined data comment.

Here is the 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(),
    ];
}

Model:

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

Why do I get a warning about array_merge_recursive()?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire