Support the ongoing development of Laravel.io →
Database Eloquent Views
Last updated 2 years ago.
0

It's so much easier to do that what you have.

  1. call your pivot table group_user (singular and alphabetic order - this is the convention so you don't have specify your foreign keys)

  2. use this code

User.php

function groups()
{
return $this->belongsToMany('Group');
}

Group.php
function users()
{
return $this->belongsToMany('User');
}


// to get all groups of a user
$user = User::find(1);
foreach ($user->groups as $group) {
echo $group->name;
}
Last updated 9 years ago.
0

I renamed the pivot table and adjusted Models but i prefer to demand the "dirty job" to the HomeController instead of doing a foreach directly in the view...

0

That's fine. it was just an example. it should still work the same way

0

Sign in to participate in this thread!

Eventy

Your banner here too?

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.