Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hsntngr's avatar

Laravel 5.5 - “Call to a member function sync() on null” Error

I'm trying to save post images. There is no problem with saving images or moving images to the uploads directory. But in sync section, it gives me that error.

(I have three tables. posts, media and pivot table)

Here is sync codes;


$media = Media::where('created_at', '>=', Carbon::now()->subSecond(10))->pluck('id');

$post->media()->sync($media, true);

Media Model;

public function posts(){
$this->belongsToMany('App\Post','media_post','image_id','post_id');

}

and Post Model

public function media() {
$this->belongsToMany('App\Media','media_post','post_id','image_id');

}

Any advice ?

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122
public function media() 
{
    return $this->belongsToMany('App\Media','media_post','post_id','image_id');
}

you are missing a return (on both relationships)

1 like

Please or to participate in this conversation.