Support the ongoing development of Laravel.io →
posted 5 years ago
Last updated 2 years ago.
0
moderator

You do a find on the role and then collect it from the relations.

If you only want the posts you can do it with (not tested):

$posts = Post::whereHas('user', function (Builder $userQuery) use ($id) {
    $userQuery->whereHas('roles', function (Builder $rolesQuery) use ($id) {
        $rolesQuery->where('id', $id);
    });
})->get();

See: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

Last updated 5 years ago.
0

Hi CreedMaicc

I think you need hasManyThrough instead of hasMany,

Watch Jefrey Way in this video: https://laracasts.com/series/eloquent-relationships/episodes/4

We are basically looking for a Role_Id through Post which belongs to a User.

$roles = App\Post::whereRoleId('some_id')->first();

$roles->posts;

and you get all the post with that role_id

It is just a idea,

Best, -Lucas Oliveira.

Last updated 5 years ago.
0

@Tobias van Beek Yes thank you, it worked perfectly, I just think the way it's done is a bit confusing, is there any way to do it more smooth? @lucas which relationship should I replace with hasManyThrough? I dont understand

0

Hi CreedMaicc,

As far as I understood you want to grab the Post Where the creator User has a Role_Id == ?,

So I did this:

roles table

  • id
  • role

users table

  • id
  • name
  • email
  • email_verified_at
  • password
  • remember_token()
  • role_id

posts table

  • id
  • name
  • user_id

=>then on Role model I did this,

protected $fillable = [
         'role',
     ];
 
public function posts(){
       
       return $this->hasManyThrough(Post::class, User::class);
       /* You do not need to provide id or foreign key, if you using the default incremented id on the Schema::, and also you do not even to have in your database for this to work */
}

=>on User I have:

public function posts()
{
   return $this->hasMany(Post::class, 'user_id');
}

=>and on Post I have:

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

=>Now you can say:

$roles = App\Role::find(role_id)->posts

You get all the Post a User wrote with this specific Role Id

Furthermore, you can say:

$roles->first()->user

And you will have such User. This was what I was saying less typing, much clean, and powerful.

I hope that helps.

Last updated 5 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

CreedMaicc creedmanic Joined 19 Apr 2019

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.