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

softwebglobe's avatar

Laravel eloquent relationship

Hello please help me, i have three tables and models

users table blogs table replies table

and the models are as below User model Blog model Reply model

the relationship i have so far are

User.php

public function blogpost()
{
    return $this->belongsTo(Blog::class);
}

public function replies()
{
    return $this->belongsTo(Reply::class)
}

Also my Blog model is as defined below

Blog.php

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

public function replies()
{
    return $this->hasMany(Reply::class)
}

and my Reply model is defined as below

Reply.php

public function blogpost()
{
    return $this->belongsTo(Blog::class);
}

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

my reply migration has the following table columns

$table->integer('user_id')->unsigned();
$table->integer('blog_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('blog_id')->references('id')->on('blogs')->onDelete('cascade');

Now my question is how do i return all the blogpost which the passed user has replied to. Example user with username Trump77 has replied to several blog posts how do i return this blogs. My user model uses username route binding and id, my blog model uses slug as primary key.

I have been trying it but it keep returning me the blog id, reply id and user.

I just want to retrieve only the full blog posts the user has replied to

0 likes
19 replies
Sergiu17's avatar
$userId = auth()->id();

Blog::with(['replies' => function($query) user ($userId) { 
    $query->where('user_id', $userId);
}])->get();

I think this is one way to do it.

softwebglobe's avatar

@JAYTHANKI - yes thank you its an api but when i ran a test using below in my controller

{
    return $user->blogpost()->get();
}

using this as usual returns all the users post but i want the blog that has the users reply

so when i do something like below i get just the

returns all the users replies but i want the post that contains the reply

softwebglobe's avatar

@SERGIU17 - Thank you but if am not mistaken i guess your code above will just return the authenticated users Blog post, i don't have problem doing this. My question is how do i return all post that the user has replied to. i guess i should be making reference to a pivot reply table

jaythanki's avatar

@SOFTWEBGLOBE if you want to get the models that have at least one related model in this relation.

$users = User::has('blogpost.replies')->get();
softwebglobe's avatar

@JAYTHANKI - Am sorry but that did not solve my problem, when i try the above codes it just pulls up random blog post with the reply table been pivote, and also pulling the user info.

I just want to fetch the post that the user has replied to and not the user or his response.

for instance when i run a query with username jeffreyway2019 for instance if he has replied to any blog post i should be able to get all the post he replied to.

construct's avatar

You should be able to do the following:

userObject()->blogpost->replies;

It also looks like you will have to loop through it so you may have to do:

foreach(userObject->blogpost as post) {
    print_r(post->replies)
}

not sure how you truly have the user model setup but also:

User::where(user......)->blogpost;

Make sure you are getting data from userObject();

softwebglobe's avatar

@CONSTRUCT - Hello sir, thank you for your response. My user, reply and blog models are as shown above in my main question. I tried your solution it did not work, it returned error.

xxxController.php
public function getMyReolies(User $user)
{
return $user->blogpost->replies;
}

running it as above returns error below "message": "Trying to get property 'blogpost' of non-object", or when i interchange the relationship i get ** "message": "Property [blogpost] does not exist on this collection instance."**, exception.

Like i said i just want to grab all the post the user has replied to

bestmomo's avatar

If you get Trying to get property 'blogpost' of non-object means that you dont get the user, so route binding is not working. How is your route ?

softwebglobe's avatar

@BESTMOMO - No sir, the binding is working, when i run below code it works perfect and returns result.

xxxController.php
public function getMyReplies(User $user)
{
return $user; // i get the user info, works fine
return $user->blogpost; //works fine returns me the posts created by the user
return $user->replies; //works fine too, returns the users replies
return $user->blogpost->replies; //which ever relationship comes first returns error when chained together
}
softwebglobe's avatar

@ROERJO - Yes you nailed it man. Thank you so much, you just saved me several hours. Can you explain the logic in the closure?

roerjo's avatar

The closure query is being performed on the replies table. So I guess if I was to translate this PHP code into English I would say:

On the replies table , find me all the replies with a user_id of {$user->id}. Now that that I have a list all the replies a user has made, join this list to the blogs table using the blog_id on the replies table. Now that I have a list of all blogs with the same ids as 'blog_id`, return this list to the user.

Not sure if that is what you meant by explain it haha. The docs link that I posted probably does a better job of explaining it.

softwebglobe's avatar

@ROERJO - sure that was what i was asking about, cause i was experimenting with sql queries to establish the right relation for my eloquent models while am trying to avoid the N + ! query problem.

Thanks again, i have gone through the laravel docs but never found that useful till you pointed me back to the same code block i was scrolling pass in the doc page. Thanks once again. I wish you are a woman will certainly kiss you. LOL

1 like
roerjo's avatar

@softwebglobe if you want to see the SQL query of that code, change ->get() to ->toSql() and then dump that result e.g.

dd(
    Blog::whereHas('replies', function ($query) use ($user) {
        $query->where('user_id', $user->id);
    })->toSql()
);
1 like

Please or to participate in this conversation.