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

tjkalinowski's avatar

Many to Many relationship

Lets assume, that we have Users and Types, and pivot type_user tables ready. We have done models User and Type relationship.

  • How to display all records in Types table one by one, and its Users assigned?
  • How to display all records in Types tables, which is of type 1 or type 2
  • Can you give me good source of example codes?
Users
id name
1 Name1
2 Name2

Types
id name
1 Type1
2 Type2

type_user
id name_id type_id
1 1 1
2 1 2
3 2 1
4 2 2

How to display example screen :
Names | Types
-------------------------
Name1 | Type1 and Type2
Name2 | Type1 and Type2
0 likes
5 replies
irsyadadl's avatar

I don't know exactly your question. But may be it can help you.

// User Model
public function types()
{
    return $this->belongsToMany(Type::class, 'types');
}
// Now you can loop them.

foreach ($user->types as $type) {
    echo $type->name;
}
2 likes
tjkalinowski's avatar

Your code not working.

     $user = User::all();
        foreach ($user->types as $type) {
            echo $type->name;
        }        

Exception in Collection.php line 1479: Property [types] does not exist on this collection instance.

irsyadadl's avatar
Level 12

Hahahah.

Actually this is going to.

$users = User::all();

foreach ($users as $user) {
    foreach ($user->types as $type) {
        echo $type->name;
    }   
}

2 likes
tjkalinowski's avatar

Thank you, this works and display all information I wanted. But now, another problem, how to display it over blade?

Should I return $users to Blade like this:

return view('types.index', compact ('users));

And then re-code the sample of code to index.blade.php :

@foreach ( $users as $user )
    @foreach ( $user->types as $type)
         {{$type->name}}
  @endofeach
@endforeach 

Please or to participate in this conversation.