Ad

Can't Get Data From Table Using Function BelongsToMany

- 1 answer

I'm trying to store students data in array with groups data. For example:

groups

id - 1
name - P1
student_id - 1

id - 2
name - P1
student_id - 2

id - 3
name - P2
student_id - 3

Here I want gate data like this

[
  {name: 'P1', students: [{id: 1, name: 'John'}, {id: 2, name: 'Liza'}]},
  {name: 'P2', students: [{id: 3, name: 'Bob'}]},
]

Tables:

users

id - bigint unsigned
name - string
...other columns

groups

id - bigint unsigned
name - string
student_id
...other columns

Group.php model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Groups extends Model
{
    public $table = "groups";
    public $timestamps = false;

    public function students(){
        return $this->belongsToMany('App\User', 'groups', 'student_id', 'id');
    }
}

UserController.php

public function groupsAdmin(){
   return view("groups", ["groups" => Groups::with(['students'])->get()]);
}

With this code I'm getting empty students array.

Ad

Answer

its, belongsToMany from users to groups so it should be like this.

you need another table(pivot table), name it group_user.

group_user table:-
user_id
group_id

and completely remove the student_id from grups table.

now go to User model and put this method:

public function groups()
{
    return $this->belongsToMany(Group::class);
}

and go to Group Model and put this code

 public function users()
 {
    return $this->belongsToMany(User::class);
 }

with this code above, you can access groups from user and users from a group, like so:

$user = User::first();
$groups = $user->groups;

Hope this helps, see the Doc here: Eloquent Many to Many relationship

Ad
source: stackoverflow.com
Ad