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

dglaser2's avatar

Adding linked table data to query builder

Hi all! I'm still getting comfortable with Laravel and am really struggling with my current project... I'm trying to implement "reposts" on my social media feed that uses Laravel for backend. I have a table for posts and a table for reposts, which contains post_id (foreign key linking to posts), user_id (who reposted), created_at (when post was reposted).

I have a query builder to find posts and a query builder to find reposts and I'd like to make a union between the two. The part I'm struggling, however, is bringing over user_id and created_at (which live on the reposts table) when I attempt the following query on the posts table: \DB::table('posts')→wherein('id', 'repost_ids')→get();

How could I achieve this? And how could I make sure there are no duplicates when I execute the union? Thank you in advance!

0 likes
1 reply
MuhammadHHassan's avatar

Hi @dglaser2 Assuming you have defined the relationship of Post, Repost and User eloquent models, you should have something like this

In app/Models/Post.php

public function reposts(): \Illuminate\Database\Eloquent\Relations\HasMany
{
    return $this->hasMany(Repost::class);
}

And in app/Models/Repost.php

public function post(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
    return $this->belongsTo(Post::class);
}

public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
    return $this->belongsTo(User::class);
}

Now you if you want to get the reposts of a certain post you can easily do

$post = \App\Models\Post::first();

// to access the user who reposted
$spot->reposts->first()->user->name;

And you better use eager loading to reduce the number of executed queries

$post = \App\Models\Post::with('reposts.user')->first();

// to access the user who reposted
$spot->reposts->first()->user->name;
1 like

Please or to participate in this conversation.