andresdevr
andresdevr

Reputation: 574

get first element from relationship eloquent

i have a question about queries, how can i get the first element from a relationship hasMany in Laravel, i have a chats table with a relationship hasMany messages, i try with this, and take() and limit(), but without success

$chats = Chat::with(['messages' => function ($query) {
    $query->first();
}])->get();

Upvotes: 2

Views: 2703

Answers (3)

andresdevr
andresdevr

Reputation: 574

I think, it can be exists another good solution, but with this i can make what i want

Chat model class:

public function firstMessage()
{
    return $this->hasOne(Message::class);
}

the query from controller:

Chat::with('firstMessage')->get();

Upvotes: 3

Pavel Lint
Pavel Lint

Reputation: 3527

I would suggest making a separate property for this and having the logic inside it. So this is inside Chat class:

public function getFirstMessageAttribute() 
{
    return $this->hasMany(Message::class)->orderBy('id', 'desc')->first();
}

And then you can call it like:

$chats = Chat::with('messages')->get();
$chats[0]->firstMessage; //

Upvotes: 1

Petr
Petr

Reputation: 460

Try this:

$chats = Chat::with(['messages' => function ($query) {
    $query->limit(1)->latest();
}])->get();

Upvotes: 0

Related Questions