Ad

Call To A Member Function Post() On Null On Many To Many Relationship

- 1 answer

I have created two table to store post information:

Posts table where I store overall information except categories.

Migration file of each table looks like this:

posts

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('slug');
        $table->longText('excerpt');
        $table->longText('description');
        $table->tinyInteger('feature')->default(1);
        $table->enum('status',['publish','draft']);
        $table->string('image');
        $table->timestamps();
    });

post_categories

Schema::create('post_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('category_id')->nullable();
        $table->unsignedBigInteger('post_id')->nullable();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->foreign('post_id')->references('id')->on('posts');
        $table->timestamps();
    });

Now, I have following function in PostCategory model:

public function post(){
  return $this->belongsToMany(Post::class);
}

Now, when I try to fetch data using following:

\App\Models\PostCategory::find(5)->post()->orderBy('created_at')->get();

I get call to member function post() on null

What should I do to get post with the category 5?

Ad

Answer

You misunderstood some concepts.

Here your relationship is between post and categories.

In post Model

public function categories(){
  return $this->belongsToMany(Category::class,'post_categories','post_id','category_id');
}

In the Category model

public function posts(){
      return $this->belongsToMany(Post::class,'post_categories','category_id','post_id');
}

Now, You're free to access posts from category and categories from post.

$post = Post::with('categories')->where('id',5)->first(); 

By this, you'll get a post with its categories.

$category= Category::with('posts')->where('id',5)->first();

By this, you'll get category with its posts.

Check more detail how many to many work

Edit:-

If by using post you want to make a condition in the categories then.

$post = Post::with('categories')->whereHas('categories', function($q){
    $q->where('id',5);
})->get();
Ad
source: stackoverflow.com
Ad