0

Hello I have Post model with relation:

public function category()
{
    return $this->belongsTo(category::class);
}

I need show posts on every tab of category. For this I need use groupBy. When I do this:

$posts = Post::with('category')->groupBy('category.title')->get();

I get error:

Column not found: 1054 Unknown column 'category.title'.

Why? How I can return my posts with key of category title?

For multilangual I use this package: https://github.com/spatie/laravel-translatable

Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
Mafys Grif
  • 557
  • 3
  • 13
  • 30
  • show the rsults of `Post::with('category')->groupBy('category.title')->dd()` probably your table name is `categories` – Shobi Dec 29 '19 at 16:39

2 Answers2

2

Try Collection's group-by method:

$posts = Post::with('category')->get()->groupBy('category.title')->all();

You may pass a callback to return the value you wish to key the group by (as you mentioned you are using laravel-translatable package):

$posts = Post::with('category')->get()->groupBy(function ($post, $key) {
    return $post->category->getTranslation('title', 'fr');
})->all();
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
0

You can use something like this:

$posts = Post::all()->groupBy('category_id')->get();

and then in blade files you can foreach tabs and find a name by category_id

knubbe
  • 1,132
  • 2
  • 12
  • 21