I have the following schema
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('userName')->default('');
$table->string('userEmail')->default('');
$table->tinyInteger('active')->default(1);
$table->timestamps();
});
Schema::create('user_groups', function(Blueprint $table)
{
$table->increments('id');
$table->string('groupName')->default('');
$table->timestamps();
});
Schema::create('users_user_groups', function(Blueprint $table)
{
$table->integer('userId')->unsigned()->index();
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade');
$table->integer('userGroupsId')->unsigned()->index();
$table->foreign('userGroupsId')->references('id')->on('user_groups')->onDelete('cascade');
$table->timestamps();
});
Essentially, a User can be apart of many Groups, and a Group can have many Users.
class User extends Model
{
protected $table = 'users';
protected $guarded = [];
public function groups()
{
return $this->belongsToMany('App\Group', 'users_user_groups');
}
}
class Group extends Model
{
protected $table = 'user_groups';
protected $guarded = [];
public function profusionUser()
{
return $this->belongsToMany('App\User', 'users_user_groups', 'userId');
}
}
I think the Models are ok. I then have an updateUsers function in my controller
public function updateUsers()
{
$users = Helper::returnUsersFromLdap();
DB::table('users')->update(array('active' => false));
foreach($users as $userName => $userData) {
$user = User::firstOrNew(['userName' => $userName]);
foreach ($userData as $userEmail => $userDepartment) {
$user->userEmail = $userEmail;
$user->active = true;
$userGroups = Helper::returnGroupsFromLdap($userEmail);
foreach($userGroups as $group) {
}
}
$user->save();
}
Session::flash('flash_message', 'Users updated');
Session::flash('flash_type', 'alert-success');
return Redirect::route('users.index');
}
I essentially get a user list from Active directory, loop this, and add the my users table. For each user, I call returnGroupsFromLdap passing the users email as a parameter. For each user, this will return the groups that user is in like so
array:3 [▼
0 => "Group1"
1 => "Group2"
2 => "Group3"
]
My question is how can I link the user groups to a user? So I loop each group and then add it to my user_groups table? But then where do I populate the pivot table I created?
Any advice on this matter appreciated.
Thanks
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire