user7986752
user7986752

Reputation:

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 ?

Upvotes: 0

Views: 1009

Answers (1)

lagbox
lagbox

Reputation: 50491

You are not returning from your relationship method. Thats why.

public function media()
{
    $this->belongsToMany(...);
}

That is what you are doing, it doesn't have a return.

$n = null;
$n->sync(); // Call to a member function sync() on null

function a() { }
a()->sync(); // Call to a member function sync() on null

This is PHP. You defined a method that doesn't return anything, you end up with a null if you call it.

Upvotes: 1

Related Questions