0

I have the following query that brings selected values from the DB (i.e. preferences that were entered by user through around 20 checkboxes):

$brng_selected = DB::table('Cprefs')
    ->where('user_id', $u_id)
    ->get();
return view('prefCat', ['b_sel' => $brng_selected]);

In the following example the user selected a preference with an id of 11 which refers to "sports" (in qatype field):

array(1) {
    [
        0
    ]=> object(stdClass)#368 (6) {
        [
            "id"
        ]=> int(47) [
            "created_at"
        ]=> string(19) "2019-09-27 12:29:59" [
            "updated_at"
        ]=> string(19) "2019-09-27 12:29:59" [
            "user_id"
        ]=> int(12) [
            "qatype"
        ]=> int(11) [
            "type"
        ]=> int(1)
    }
}

Now I need to configure the sports checkbox below to be checked based on the above. How can this be done?

<input type="checkbox" name="catpref[]" value=11 > Sports<br>

<input type="checkbox" name="catpref[]" value=1> Politics<br>
6
  • What did you try so far? Commented Sep 27, 2019 at 12:37
  • How you generate checkboxes ? dynamic or static? Commented Sep 27, 2019 at 12:49
  • static check boxes Commented Sep 27, 2019 at 12:49
  • And you get selected value from DB and want it checked if ID exists,right Commented Sep 27, 2019 at 12:56
  • This is correct Commented Sep 27, 2019 at 12:56

2 Answers 2

1

Get the column which you need to compare as below

$brng_selected = DB::table('Cprefs')
    ->select('qatype') // column name which you need
    ->where('user_id', $u_id)
    ->get()->toArray(); // it will return as array

return view('prefCat', ['b_sel' => $brng_selected]);

In your view change as below :

<input type="checkbox" name="catpref[]" value=11 {{ (in_array(11,$brng_selected)?"checked":'') }} > Sports<br>
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this?

@if ($ba_sel->qa_type == 11)
    <input type="checkbox" name="catpref[]" value="11" checked>Sports<br>
@else
    <input type="checkbox" name="catpref[]" value="11">Sports<br>
@endif

4 Comments

Yes but checked instead of selected
Are your checkboxes generated dynamicaly?
Undefined variable: item. I changed it to $b_sel , but gave me error : Undefined index: qatype
$item was just for the example, in your case, it must be $b_sel[0]['qatype']. Now on to the question, if the checkboxes are static, I do not see another way of doing this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.