1

I'm trying to pass an array from Controller to Blade My Controller:

public function socaucuachuong($id){
    $socaucuachuong = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
    return view('DeThi::dethi')->with('socaucuachuong', $socaucuachuong);
}

My Blade file:

$('select').select();
function get_units(id) {
    var list = $('#dschuong');
    list.empty();
    var url = "{{ route('dethi.socaucuachuong') }}"+'/'+ id;
    var success = function (result) {
        if (result.length <= 0) {
            var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
            list.append(item);
        } else {
            for (i = 0; i < result.length; i++) {
                var item = '<div class="input-field"><label for="unit-' + result[i].chuong + '">Nhập số câu hỏi chương ' + result[i].chuong + ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')"  name="unit-' + result[i].chuong + '" id="unit-' + result[i].chuong + '" required></div>';
                list.append(item);
            }
        }
    };
    $.get(url, success);
}

My Route file:

Route::post('socaucuachuong', 'DeThiController@socaucuachuong')->name('dethi.socaucuachuong');
hoah99
  • 21
  • 4
  • What is the problem, what is your question? You are passing `$socaucuachuong` as an array to your view, if you do something like `{{ print_r($socaucuachuong) }}` you will see it, and you can use it ... what is the problem? – Don't Panic May 02 '21 at 08:16
  • how can I get 2 values `chuong`, `Total` of `$socaucuachuong` and use it in js function? – hoah99 May 02 '21 at 09:54
  • `var chuong = {{ $socaucuachuong['chuong'] }};` – Don't Panic May 02 '21 at 11:02
  • Does this answer your question? [How to access PHP variables in JavaScript or jQuery rather than ](https://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-vari) – Don't Panic May 02 '21 at 11:05

1 Answers1

0

You can get array values in blade like this.

<script>
var socaucuachuong = @JSON($socaucuachuong); // this will be array value.
</script>

LoveCoding
  • 1,121
  • 2
  • 12
  • 33