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

tgezginis's avatar

Laravel 4 Eloquent group by relationship date

I have a topics and links tables on Laravel 4.2 with Eloquent ORM. They have a relationship like this;

Topic model:

class Topic extends \Eloquent {
    public function links()
    {
        return $this->belongsToMany('Link');
    }
}

Link model:

class Link extends \Eloquent {
    public function topics()
    {
        return $this->belongsToMany('Topic');
    }
}

I want to group links like this;

05.02.2015

First Topic

  1. Sample link
  2. Sample link

Second Topic

  1. Sample link
  2. Sample link

04.02.2015

First Topic

  1. Sample link
  2. Sample link

Second Topic

  1. Sample link
  2. Sample link

Database scheme

topics

  • id
  • name
  • created_at
  • updated_at

links

  • id
  • title
  • created_at
  • updated_at

link_topic

  • id
  • link_id
  • topic_id

How can I do this? I didn't solve this problem.

Thanks.

0 likes
4 replies
pmall's avatar
pmall
Best Answer
Level 56

You have to group the topics collection.

$topics_collection = Topic::all();

$topics_groups = $topics_collection->groupBy('created_at');
@foreach($topics_groups as $date => $topics)
  {{ $date }}
  @foreach($topics as $topic)
    {{ $topic->name }}
    @foreach($topic->links as $link)
      {{ $link->title }}
    @endforeach
  @endforeach
@endforeach

Not sure but I think the date here will be a timestamp. You may use https://github.com/briannesbitt/Carbon to format it like any other date in laravel.

3 likes
JarekTkaczyk's avatar

@tgezginis You should've added, that you want to group by the date on link, correct? Or maybe date from the pivot table.. Be specific.

Oh, and btw show the result you expect in a more detailed manner. Now, being the relation m-m it's rather hard to guess what you need exactly.

tgezginis's avatar

@pmall it works. I added only last_link_update column to topics table and I group by this column. Thanks ;)

Please or to participate in this conversation.