How to order a Laravel hasMany relationship?

October 26, 2018

You can simply add a ->orderBy() to the hasMany relationship

<?php

class YourModel {
// ...
function posts(): HasMany {
    return $this->hasMany(Post::class)
           ->orderBy('updated_at');
}

}