I am building a small blog and I would like to use the built-in Eloquent eager loading, but I would like it to act as an explicit join.
Here's what I'm trying to do, using a join, which works, but not in the way I want.
$posts = Post::join('users', function($join){
$join->on('users.id', '=', 'posts.user_id');
$join->on('users.status', '=', DB::raw('active'));
})
->get();
My problem with this is that I can't use the user model on my post like so:
$posts[0]->user->firstname;
With the join, the user's data is directly set on the post model, so I have to use it like so:
$posts[0]->firstname;
The thing is: I would like to use my User model because it has a few method inside that I'd like to use. One for printing the full name, one for printing its URL, etc..
What I am not able to do with eager loading, is to prevent a post from loading when it has no user attached to it. When the user associated with the post doesn't have the status 'active', I still get the post, and NULL for the user. But I don't want the post at all.
Is that something possible? Am I being clear enough in my explications?
Thanks