2

I am printing the notifications for a Model in Laravel 5:

@foreach ($booking->notifications as $notification)                     
        <div class="message">
            <div class="myMessage">
              <p>{{ $notification->data[0])}}</p>
            </div>
        </div>                      
@endforeach

These notifications are being printed in descending order, is there a way I can change this so they print in ascending order?

The Laravel documentation states:

By default, notifications will be sorted by the created_at timestamp

It's worth mentioning that there are multiple Notification classes that have been used with this model so I'm not sure if that affects the sorting behavior?

user3574492
  • 6,225
  • 9
  • 52
  • 105
  • 1
    Can you show how you have your relation set up? – DevK Jun 25 '17 at 00:31
  • Yeah, it would be easier if we knew what the code in your controller looked like. – Derek Pollard Jun 25 '17 at 00:34
  • Why would you want to see the controller? It has nothing to do with the way notifications work in Laravel. If you have specified `use Notifiable;` in your model then Laravel automatically associates the model with any Notification records using the model->id – user3574492 Jun 25 '17 at 00:36
  • You should be doing all your code processing and data retrieval in the controller, not the view. – Derek Pollard Jun 25 '17 at 01:35
  • since you are receiving the notification as a collection, I think the cleanest way is to use collection functions to do any operation on the result. – Peyman Jun 25 '17 at 03:57
  • @Derek There is no code processing going on, it's a simply control statement that is looping over a collection and printing the data. it's perfectly fine to keep presentation logic in the view, as long as it is 'presentation logic'. – user3574492 Jun 25 '17 at 15:15
  • @PeymanSeraj I don't follow, can you elaborate? Maybe with an example? – user3574492 Jun 25 '17 at 15:16
  • I am glad you found the answer. – Peyman Jun 25 '17 at 17:47

2 Answers2

7

@Peyman Seraj led me in the right direction here.

With Laravel collections you can use collection methods, so I used the sortBy() method on my collection:

@foreach ($booking->notifications->sortBy('created_at') as $notification)

This now prints the data in ascending order.

user3574492
  • 6,225
  • 9
  • 52
  • 105
5

Just stump upon the issue: by following the Notifiable trait i found the relation has order assigned to it.

You can override it in your model:

public function notifications()
{
    return $this->morphMany(\Illuminate\Notifications\DatabaseNotification::class, 'notifiable')->orderByRaw('-read_at','DESC')->orderBy('created_at','DESC');
}

in my case i was going for the unread first then the rest. If you wanna set the sort on your query just use plain relation:

public function notifications()
{
    return $this->morphMany(\Illuminate\Notifications\DatabaseNotification::class, 'notifiable');
}
MichałKraków
  • 111
  • 1
  • 7