简体   繁体   中英

How to pass an array data from controller to blade file Laravel

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

You can get array values in blade like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM