How to apply filters in a belongsToMany relation in Laravel 5.8?

Asked

Viewed 73 times

0

I have a table posts, a table categorias and a pivot table categoria_post, where a post may be associated with many or no category.

In my model categoria and post I have the methods respectively categorias and posts in a relationship belongsToMany.

public function posts(){
        return $this->belongsToMany('App\Models\post','categoria_post','categoria_id','post_id');
    }

public function categorias(){
    return $this->belongsToMany('App\Models\categoria','categoria_post','post_id','categoria_id');
}

In the posts table I have a field is_active and rate.

I want to present so in the browser:

  1. Show the list of 8 posts mais votados (rate) and ativos (is_active==1) and which are associated with at least one category,
  2. Display a list of all categories and all active posts (is_active==1) that are related to each of them.

BROWSER


(os 8 posts ativos mais votados)
post 1, post 2, post 3, post 4, post 5, post 6, post 7, post 8 


(Todos os posts ativos por categoria)

Categoria 1
post 1, post 2,

categoria 2
post 1, post 3,

categoria 2
post 1, post 3, post 7,

...

How do I achieve this using the smallest number of foreach possible?

Is there any way in the Category Template within the posts function (belongToMany) to filter only active posts (is_active==1)?

1 answer

0

If you are creating the templates in the Eloquent pattern, just add the conditions

Example:

$posts = App\Post::where('is_active' => 1)->orderBy('rate', 'desc')->take(8)->get();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.