简体   繁体   中英

laravel get related posts by tags

I want to get the related posts of a current post by tags but honestly I can't get it.

I will show you my tables structure.

Posts Table:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('body');
        $table->text('excerpt')->nullable();
        $table->string('stickers')->nullable();
        $table->integer('category_id')->nullable()->unsigned();
        $table->text('meta_description')->nullable();
        $table->text('meta_keywords')->nullable();
        $table->string('postimg')->nullable();
        $table->string('type')->nullable()->default('common');
        $table->boolean('published')->default(false);
        $table->softDeletes();
        $table->timestamps();
    });
}

Tags Table:

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('slug')->unique();
        $table->softDeletes();
        $table->timestamps();
    });
}

I have a pivot table to handle tags on posts and posts with those tags.

post_tag table:

public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id')->unsigned();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

        $table->integer('tag_id')->unsigned();
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
    });
}

Everything is working good, one tag have many posts and one post have many tags, is a many to many relationship.

Post Model:

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

Tag Model:

public function posts()
{
  return $this->belongsToMany('App\Post');
}

I can display all the tags on a post but i want to display the related posts by tags, when i say related posts i meaning to "the current post" that visitor is reading. Let's say that this current post have a microsoft, google, apple, cars tags, i want the related posts to those tags. I don't know if that's possible or is easyer to do ir by categories.

News Controller logic:

Here's where i have all the logic to the post view.

public function getSingle($slug, $id = null)
{
    $post = Post::where('slug', '=', $slug)->first();
    $topcat = Category::orderBy('created_at', 'desc')->limit(5)->get();
    $comment = Comment::find($id);

    $tags = Tag::all();
    $tags2 = array();
    foreach ($tags as $tag) {
        $tags2[$tag->id] = $tag->name;
    }

    // Previous and Next Post
    $previous = Post::where('id', '<', $post->id)->orderBy('id', 'desc')->first();
    $next = Post::where('id', '>', $post->id)->orderBy('id', 'asc')->first();

    // Related Posts Here!

    $tags3 = array();
    foreach ($post->tags as $tag) {
        $tags3[$tag->id] = $tag->name;
    }
    $related = Post::whereHas('tags', function ($query) use ($tags3) {
        $query->where('name', $tags3);
    })->get();
    // dd($related);

    return view('news.single')
            ->withPost($post)
            ->withTopcat($topcat)
            ->withTags($tags2)
            ->withComment($comment)
            ->withPrevious($previous)
            ->withNext($next)
            ->withRelated($related);
}

I did the $tags3 variable to test it that way but i didn't get what i wanted.

Thanks in advance

This should work:

$post = Post::where('slug', '=', $slug)->first();

$related = Post::whereHas('tags', function ($q) use ($post) {
    return $q->whereIn('name', $post->tags->pluck('name')); 
})
->where('id', '!=', $post->id) // So you won't fetch same post
->get();

The $post->tags->pluck('name') line creates an array of all the tag names (that belong to the post).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM