How to get posts of people I am following in Eloquent - laravel

I have a User model, a Post model.
In my User model, I have the following:
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')->withTimestamps();
}
public function following()
{
return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')->withTimestamps();
}
public function posts()
{
return $this->hasMany(Post::class);
}
So basically, $user->following gives me a collection of users I am following and $user->posts gives me the collection of posts. I want to do this:
$posts = [];
$user->following->each(function($f) use($posts) {
$posts[] = $f->posts;
});
but more Eloquenty way, if that makes sense. Because I want to paginate the result after this. I was thinking of doing hasManyThrough, but cannot figure out how?

Here is link to similar question with an answer.
I think you wan tot do something like this:
User::where('id', $id)->with(['following.posts' => function ($q) use (&$posts) {
$posts= $q->get()->unique();
}])->first();

Related

Eloquent collections with a relation of another relation

I have Post eloquent related with PostCategory and my collection is good.
class Post extends Model
{
public function post_categories()
{
return $this->belongsTo(PostCategory::class, 'category_id');
}
public function detail($slug_category, $slug)
{
$detail = Post::with('post_categories')
->whereHas('post_categories', function ($query) use ($slug_category){
$query->where('category_slug', $slug_category);
})->where('slug', $slug)
->first();
return($detail);
}
}
I have this another class 'Players' where i need to have a collection with all user's posts with PostCategory category relation.
class Players extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
public function detail($slug_category, $slug_name)
{
$detail = Player::with('posts')
->whereHas('players_info', function ($query) use ($slug_name){
$query->where('slug', $slug_name);
})
->whereHas('player_categories', function ($query) use ($slug_category){
$query->where('category_slug', $slug_category);
})->first();
return($detail);
}
}
I read something about "belongsToMany" and "withPivot", but I'm still confused for correct way.
What can I do to resolve this?
thanks!
I solved just with this.
return $this->hasMany(Post::class)->with('post_categories');

Laravel get all user who comment on post via post

Ive been trying to get all user who commented on post
$post->comments()->user() //does not work
$post->comments()->load('user', function($q) { $q->select('email'); }));//does not work
$post->comments()->with('user')->get() //worked but not getting the user as result (still need to loop)
but im getting a BadMethodCallException
this are the models
//Comment Model
public function user(){
return $this->belongsTo(User::class);
}
public function post(){
return $this->belongsTo(Post::class);
}
//User Model
public function comments(){
return $this->hasMany(Comment::class);
}
public function posts(){
return $this->hasMany(Post::class);
}
//Post Model
public function user(){
return $this->belongsTo(User::class);
}
public function comments(){
return $this->hasMany(Comment::class);
}
you can try getting all comments belongs to that post with their users:
$users= Comment::where('post_id', $post->id)->with('user')->pluck('user');
I found an answer (i think this is a duplicate question, but anyway)
Laravel get all posts that a user commented on
Instead i use this
$post->whereHas('comments', function($query) use($user) {
$query->where('id',$user->id);
})->get();

how to connect multiple tables with Laravel models

I am using Laravel 7.
I want to retrieve all the users that are active and belong to Austria.
I would like to do that using laravel relationships.
There are three tables that should be connected through the models: countries, users and user_details.
Country.php:
public function user_details()
{
return $this->hasMany('App\UserDetail', 'citizenship_country_id', 'id');
}
User_detail.php:
public function country()
{
return $this->belongsTo('App\Country', 'citizenship_country_id', 'id');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
User.php:
public function user_detail()
{
return $this->hasOne('App\UserDetail', 'user_id', 'id');
}
In the controller I used the following code to retrieve all austrian users that are active:
return Country::where('name', 'Austria')->first()->user_details()->first()->user()->where('active', '1')->get();
I should visualize two users but I get only one user. I suppose the error is the second first.
Can help?
Try This.
$users = User::whereHas('user_details.country', function ($query) {
$query->where('countries.name', "Austria");
})
->where("active",1)
->get();

Eloquent Relationship. Has Many relation with different keys

Background
I have a model, Contract that belongs to the User model through two keys, user_id and recipient_id. How would I be able to query all the contracts for a user using $user->contracts keeping the two key into consideration.
\App\Contract model has this
$protected $fillable = [
...
'user_id',
'recipient_id',
...
];
public function user ()
{
return $this->belongsTo(User::class);
}
public function recipient()
{
return $this->belongsTo(User::class, 'recipient_id', 'id');
}
\App\User model has this
public function contracts ()
{
return $this->hasMany(Contract::class);
}
To get the user contracts, I have to do this
$contracts = Contract::where('user_id', $user->id)
->orWhere('recipient_id', $user->id)
->get();
What I would like is something like this. \App\Contract
public function user () {
return $this->belongsTo([User::class, User::class], ['user_id', 'recipient_id']);
}
I am aware of https://github.com/staudenmeir/eloquent-has-many-deep and it doesn't solve my problems.
How do I go about it?
I couldn't find a way, so, I ended doing this in ContractController.php
public function index()
{
$user = Auth::user();
if ($user->isAdmin()) {
return Contract::latest()->get();
}
$contracts = Contract::where('user_id', $user->id)
->orWhere('recipient_id', $user->id)
->get();
return $contracts;
}

Merging two queries into one using Eloquent

I have this two queries to display information in 3 tables Users, Comments, and Posts. so I made this function:
public function show($id)
{
$posts = Post::with(['comments'])->findOrFail($id);
$user = User::find($posts->user_id);
echo "<h1>".$posts->title.'</h1>';
echo "<h2>".$user->name.'</h2>';
foreach ($posts->comments as $comment) {
echo $comment->body.'<br>';
}
}
on this function I using two variable $posts and $user, can I merge this two variable using eloquests command like Post::with(['user','comments'])'? so I can use just $posts variable and use it like $posts->users->name to access user name.
i was trying using this way:
$posts = Post::with(['comments','users'])->findOrFail($id);
but when i echo the post it showing that the user was null:
{"id":1,"user_id":1,"title":"Oleh id 1","body":"ini adalah content","created_at":"2017-10-18 03:25:54","updated_at":"2017-10-18 03:25:54","comments":[{"id":1,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:50","updated_at":"2017-10-18 03:43:50"},{"id":2,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:53","updated_at":"2017-10-18 03:43:53"},{"id":3,"post_id":1,"body":"Keren banget deh artikelnya, TOP","created_at":"2017-10-18 03:43:54","updated_at":"2017-10-18 03:43:54"}],"users":null}
Here's my model if you need it. My post model:
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users(){
return $this->belongsTo('App\User');
}
}
my Comment model
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
You’ll have an easier time sticking to Laravel’s conventions for naming relationships.
A Post has many Comments, which belong to a User. Given this set up:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
You can then query a post’s comments and users like this:
$comments = $post->comments()->with('user')->get();
You could also eager-load the user relation on comments if you always wanted the user returned with a comment:
class Comment extends Model
{
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Then your query would be simplified:
$comments = $post->comments;
Hope this helps you!!
What I am guessing is you want the list of all posts with the users. If relation is defined, try with the join
$posts = DB::table('posts')
->join('users', 'users.id', '=', 'posts.user_id')
->select('posts.*', 'users.name as user_name')
->where('posts.comments', '<>', NULL)
->get();
#NOTE: If you are using soft deletes you might wanna add where('posts.deleted_at', null)
After couple of days searching finally i got the answer, i can get merge the query like this:
$posts = Post::with(['comments','users'])->findOrFail($id);
but in the Post Model the function not "Users" but "User".

Resources