@fdusautoir A few suggestions:
// this is bad:
public function lastMessage()
{
// always TRUE, since messages() returns an object.
// if you instead tried $this->messages, result would be the same,
// because again, it's an object (collection), that evaluates to true as well.
if($this->messages())
return $this->messages()->orderBy('created_at', 'DESC')->first();
// so it never happens
return false;
}
public function isAnswered()
{
if($this->lastMessage()) // first query
return ($this->lastMessage()->auth_id) // again the same query
? $this->lastMessage() : false; // and once again the same query = 3 queries
return false;
}
Now, if you're working with Eloquent, then I suggest Eloquent way of handling it:
// Conversation model
/**
* Conversation has one latest Message.
* as dynamic property returns \CeProtelco\ConversationMessage|null
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function latestMessage()
{
return $this->hasOne('CeProtelco\ConversationMessage', 'conversation_id') // FK might be ommited here
->latest();
}
/**
* Determine whether the conversation has been answered (by the admin?).
*
* @return bool
*/
public function isAnswered()
{
// check whether latestMessage is not NULL, then check its auth_id
return ($this->latestMessage && $this->latestMessage->auth_id);
}
then simply:
$conversation->latestMessage; // Message model OR null if no related messages were found
$conversation->isAnswered(); // bool