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

shahzadbuckstec's avatar

Make relation with pivot table

I have post, hashtag tables, I made a pivot table "post_hashtag_pivot" to save post_id and hashtag_id in this table instead of comma separated hashtags in post table.

Now I want to get those posts which have a specific hashtag i.e. 'nice'.

But I'm not succeeded yet.

Post table

id, title

Hashtag table

id, name

Post hashtag pivot table

id, post_id, hashtag_id

I have three models

Post
Hashtag
PostHashtagPivot

I made this relation in Hashtag model

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Hashtag extends Model{
    public function posts()
    {
        return $this->belongsToMany('App\Models\Post', 'post_hashtag_pivot', 'hashtag_id', 'id');
    }
}

Is any one guide me through how to make this relation working so I can get posts with hashtag?

Thanks

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122
public function posts()
{
    return $this->belongsToMany('App\Models\Post', 'post_hashtag_pivot', 'hashtag_id', 'post_id');
}

and then in the Post model

public function hashtags()
{
    return $this->belongsToMany('App\Models\Hashtag', 'post_hashtag_pivot', 'post_id', 'hashtag_id');
}


you don't reference the id on the pivot table.

and then

$tag = 'nice';

$nicePosts = Post::whereHas('hashtags', function($query) use($tag){
                $query->where('name',$tag);
            })->get();
1 like
Snapey's avatar

Please mark best answer. Thanks :)

Please or to participate in this conversation.