Search code examples
laravelmany-to-manyrelationship

laravel many to many ralationship 01


How can I get role_id laravel many to many relationships

[
    {
        "id": 1,
        "name": "Add",
        "slug": "menu/store",
        "created_at": "2018-02-27 19:01:00",
        "updated_at": "2018-02-27 19:01:00",
        "pivot": {
            "role_id": 1,
            "menuitem_id": 1
        }
    }
]

Hello dear please help me to solve it Thank you


Solution

  • Retrieve a single object of main table, then use pivot:

    foreach ($user->roles as $role) {
        echo $role->pivot->role_id;
    }
    

    You can get more information and other helpers on Laravel Documentation - Many to Many Relationships