Populate field values from where() parameter in hasMany() relation

Posted 3 months ago by v4np3rs13

Hello, I have been struggling with this problem for days, and I simply cannot find a proper and D-R-Y solution.

I have two models. App\User and App\Comments.

I am trying to find all hot comments for a specific user. And populate the 'hot' column, while inserting the values for the user.

The thing which is working now...

User.php:

public function hot_comments() {
    $this->hasMany(Comment::class)->where('hot', true);
}

I fetch the hot comments by:

$user->hot_comments or $user->hot_comments()->get();

And while inserting, I use this:

$user->hot_comments()->create([
    "hot" => true
]);

So basically, on inserting, I must explicitly enter the 'hot' column value. Can I just fetch it from the relation query somehow, so I clean up the code. Maybe something like withPivotValue() in BelongsToMany relation.

Is there are Laravel method available for this ?

Thank you in advance.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.