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

fcode's avatar
Level 7

Laravel: Order query using relationship

Hello guys. Please, I need help with the following issue. I have two tables, user and contents. users has many contents and content belongs to user.

I want to query:

  1. All users with their contents ordered by the users with the most recent content
  2. users with their contents that were uploaded within the last 24hrs

Any suggestion with working code samples will be appreciated.

0 likes
3 replies
tisuchi's avatar

@fcode

User.php

    public function contents()
    {
        return $this->hasMany(Content::class)->orderBy('updated_at');
    }

Content.php

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

Now, in the controller, you can write the query like this way-

// Getting all latest contents of user ID = 1
$contents = User::with('contents')->findOrFail(1);

// Getting all latest contents of user ID = 1
$contentsInLast24Hours = User::with('contents', function ($query) {
    $query->where('created_at', '>=', now()->subDay(1));
})->findOrFail(1);
1 like
fcode's avatar
Level 7

Thanks, @michaloravec for the article. I wonder why Google did not find the article during my googling

Please or to participate in this conversation.