Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dr24's avatar
Level 2

Problem with retrieving selected checkboxes from database in Laravel

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'));
}

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.

0 likes
14 replies
MichalOravec's avatar

Something like this

<select name="sport_id" multiple>
    @foreach ($sportsOptions as $option)
        <option value="{{ $option->id }}" {{ $userSportsOptions->contains('sport_id', $option->id) ? 'selected' : '' }}>{{ $option->name }}</option>
    @endforeach
</select>
dr24's avatar
Level 2

@michaloravec

With this I get dropdown menu and I need checkbox and also it returns just all values and there is no selected ones.

MichalOravec's avatar

Sorry


@foreach ($sportsOptions as $option)
    <input type="radio" name="sports[]" value="{{ $option->id }}" {{ $userSportsOptions->contains('sport_id', $option->id) ? 'checked' : '' }}>{{ $option->name }}
@endforeach

When you dump($userSportsOptions); what do you get?

1 like
dr24's avatar
Level 2

@michaloravec

Yeah, now shows checkboxes, but still it lists all values and it doesn't show (checked) those selected values. For some reason it looks like this part won't work {{ $userSportsOptions->contains('sport_id', $option->id) ? 'checked' : '' I get this when I dump

 Illuminate\Database\Eloquent\Collection {#1671 ▼
 #items: array:7 [▼
    0 => App\UserSport {#1711 ▶}
    1 => App\UserSport {#1712 ▶}
    2 => App\UserSport {#1713 ▶}
    3 => App\UserSport {#1714 ▶}
    4 => App\UserSport {#1715 ▶}
    5 => App\UserSport {#1716 ▶}
    6 => App\UserSport {#1717 ▶}
   ]
  }

Those are seven values that are in user_sport table for this user. in this case, football, handball and etc. There are 12 values in all, for this user it shows 7 like it is supposed to

Snapey's avatar

You get the idea. you need two lists. The first is ALL possible checkbox options.

You loop over these however you need to create the list of checkbox options.

Now the second list is an array of the checkboxes previously chosen.

As you output each item from list 1, you check if the item is contained in list 2, if so, mark it checked.

change this line to get a simple array

$userSportsOptions = UserProfile::findOrFail($profileId)->sports()->modelKeys();

and check what you are getting before going to the html

1 like
dr24's avatar
Level 2

@snapey

Can you show me an example for that? I know how to do first part the second I have problem with

MichalOravec's avatar

@dr24 dump($userSportsOptions->toArray()); Could you post what is result as array?

dr24's avatar
Level 2

@michaloravec

array:7 [▼
0 => array:5 [▼
    "id" => 2
    "name" => "Handball"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 2
    ]
]
1 => array:5 [▼
    "id" => 4
    "name" => "Swimming"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 4
    ]
]
2 => array:5 [▼
    "id" => 7
    "name" => "Bodybuiling"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 7
    ]
]
3 => array:5 [▼
    "id" => 8
    "name" => "Tennis"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 8
    ]
]
4 => array:5 [▼
    "id" => 9
    "name" => "Volleyball"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 9
    ]
]
5 => array:5 [▼
    "id" => 10
    "name" => "Biking"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 10
    ]
]
6 => array:5 [▼
    "id" => 12
    "name" => "Hockey"
    "created_at" => "2020-04-29 19:02:49"
    "updated_at" => "2020-04-29 19:02:49"
    "pivot" => array:2 [▼
    "user_id" => 1
    "sport_id" => 12
    ]
]
]
Snapey's avatar
Snapey
Best Answer
Level 122

A simple example for permissions;

@foreach($permissions as $permission)
    <div class="w-full py-1">
        <label>
          <input type="checkbox" class="mr-2" name="permissions[]" value="{{ $permission->id }}"
            {{ $userPermissions->contains('id',$permission->id)? 'checked': ''}}   // this is the important line
            >{{ $permission->name }}
        </label>
    </div>
@endforeach
1 like
dr24's avatar
Level 2

@snapey

When I dump $userSportsOptions I get Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::modelKeys()

MichalOravec's avatar
@foreach ($sportsOptions as $option)
    <input type="radio" name="sports[]" value="{{ $option->id }}" {{ $userSportsOptions->contains('pivot.sport_id', $option->id) ? 'checked' : '' }}>{{ $option->name }}
@endforeach
1 like

Please or to participate in this conversation.