My code works. But I'm not sure is it a best solution. I need option to display user players and / or players from a group user belong to. Thank you for you time.
$user = $request->user();
$userGroups = $user->groups;
$friendsPlayers = [];
foreach ($userGroups as $group) {
$groupUsers = $group->users;
foreach ($groupUsers as $groupUser) {
if ($groupUser->id !== $user->id) {
$userPlayer = $groupUser->players;
foreach ($userPlayer as $player) {
if (!in_array($player, $friendsPlayers)) {
$friendsPlayers[] = $player;
}
}
}
}
}
1.Schema/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('info');
$table->timestamps();
});
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('name');
$table->string('url');
$table->string('type');
$table->integer('wins');
$table->integer('lost');
$table->integer('draws');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('group_user', function (Blueprint $table) {
$table->integer('group_id')->unsigned()->nullable();
$table->foreign('group_id')->references('id')
->on('groups')->onDelete('cascade');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
$table->timestamps();
});
2.Models/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Group extends Model
{
protected $fillable = [
'name', 'info',
];
public function users() {
return $this->belongsToMany(User::class);
}
}
class Player extends Model
{
protected $guarded = [];
public function user() {
return $this->belongsTo(User::class);
}
public function leagues() {
return $this->belongsToMany(League::class)->withPivot('win', 'lost',
'draw')->withTimestamps();
}
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function players() {
return $this->hasMany(Player::class);
}
public function leagues() {
return $this->hasMany(League::class);
}
public function scoreboards() {
return $this->hasMany(Scoreboard::class);
}
public function groups() {
return $this->belongsToMany(Group::class);
}
}