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

manof360's avatar

Orderby created_at , desc - many to many

I know this common problem and I should find the error , really I search and try a lot but I cannot realise the mistake .

I have 3 tables

1- recruitments
2- governorates
3- categories

between the recruitments and the governorates many-to-many Relationships I made every thing in corrects way

this is the model

class recruitment extends Model
{
    protected $fillable = ['........'];

    public function scopeActive($query)
    {
        return $query->where('publish', 1);
    }

    public function governorates()
    {
        return $this->belongsToMany(Governorate::class)->withTimestamps();
    }
 public function categories()
    {
        return $this->belongsToMany(Category::class)->withTimestamps();
    }
}

and this is the other model


class Governorate extends Model
{
    protected $fillable = ['.......'];


    public function recruitmentes()
    {
        return $this->belongsToMany(recruitment::class);
    }
}

I try this: https://laraveldaily.com/get-newest-oldest-records-from-pivot-table-in-belongstomany/ and this : https://stackoverflow.com/questions/49928725/sorting-a-laravel-collection-by-many-to-many-pivot-table-column

now by forelse I get data but when I add new record it's not shown in the top of table my questions How can I get data form recruitments in descending order according to created_at ? and shows the last record first.

thanks in advances

0 likes
1 reply
bobbybouwmann's avatar
Level 88

You can order them like so

$governates = Governorate::with('recruitments' => function ($query) { 
    $query->orderBy('governorate_recruitement.created_at', 'DESC');
}]);

@foreach($governates->recruitments as $recruitment)
	// Do your magic
@endforeach

Please or to participate in this conversation.