I am trying to retrieve all checkbox values from database and those values that are selected need to be checked. I have many to many relationship between models and I currently am able to retrieve all values from database and to write them in blade or those values that are just selected (it is one OR the other) but I can't seem to find solution to retrieve them all that exist in database and those that are selected to be checked. Any help is appreciated. Here is my code and database tables.
user_profiles table
id user_id first_name
1 1 Mike
sport table
id name
1 Football
2 Basketaball
3 Handball
4 Etc...
user_sport table
id user_id sport_id
1 1 1
2 1 2
UserProfile.php
public function sports()
{
return $this->belongsToMany(UserSport::class, 'user_sport', 'user_id', 'sport_id');
}
UserSport.php
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_sport', 'sport_id', 'user_id');
}
UserProfileController.php
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$sportsOptions = UserSport::get();
$userSportsOptions = UserProfile::findOrFail($profileId)->sports()->get();
return view('profile.show', compact('sportsOptions', 'userSportsOptions'));
}
show.blade.php
@foreach($sportsOptions as $sportsOption)
<label class="checkbox-inline">
<input type="checkbox" id="sport" name="sport[]" value="{{$userSportsOptions->id}}"> {{$userSportsOptions->name}}
</label>
@endforeach
So, I know that naming conventions aren't great but relationship works and with foreach and $sportsOptions in blade in this case and example it displays all four values from sport table and with $userSportsOptions it displays those two values (selected values). I need help on how to achieve that displays in blade all values and those that are selected to be selected.