Mirsad Batilovic Mirsad Batilovic - 3 months ago 16
PHP Question

Laravel 5.2 - select posts by tag and order descending

I stack in my Laravel project with posts selected by tag with ordering by descending. I want to show posts by specific tag. I create a

Post
and
Tag
models with
manyToMany
relations. I also create a pivot table
post_tag
with
post_id
and
tag_id
. In PostsController I create
tags()
method:

public function tags($tagid)
{
$tag = $this->tags->find($tagid);

return view('frontend.posts.tag', compact('tag'));
}


and loop it in view:

@foreach($tag->posts as $post)
{{ $post->title }}
....
@endforeach


This works for me, but i need to order posts by
posts.created_at
in descending order. How to make query using Tag::find($id) but order it by posts.created_at field in Posts table? Here is my Post and Tag models with manyToMany relations:

class Post extends Model
{
.....

public function tags()
{
return $this->belongsToMany(Tag::class);
}
.....


and

class Tag extends Model
{
protected $fillable = ['name'];

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


Please, how to order posts selected by specific tag in descending order by
created_at
column in
posts
table? I will also want to use paginate() metohd in that query in descending order. Please help.

Answer

I find solution and here is answer

For descending ordering in Tag model posts() method should be:

public function posts()
    {
        return $this->belongsToMany(Post::class)->orderBy('created_at', 'desc');
    }

find() method in TagController should be like this:

public function tags($tagid)
    {
        $tag = $this->tags->find($tagid)->posts()->paginate(12);

        return view('frontend.posts.tag', compact('tag'));
    }

and in blade:

@foreach($tag as $post)
    {{ $post->title }}
@endforeach