Laravel - passing php variable to JS as array

68
February 26, 2018, at 07:37 AM

Im trying to pass result from database to js variable as array:

        $test_min_max_list = TestsMinMax
        ::join('results', 'tests_min_max.id', '=', 'results.test_result_id')
        ->select('created_at','min','avg','max')
        ->where([
            ['results.user_id', '=', $user_id],
            ['results.test_id', '=', $request->get('test_id')],
        ])->get();

Return view for variable:

    return view('results', [
        'test_min_max_list' => $test_min_max_list
    ]);

Result on page:

{{$test_min_max_list}}

->

[{"created_at":"2018-01-13 22:47:17","min":0.29999999999999999,"avg":0.40000000000000002,"max":0.53000000000000003},{"created_at":"2018-01-13 22:48:58","min":0.29999999999999999,"avg":0.76300000000000001,"max":1.972},{"created_at":"2018-01-13 22:54:51","min":0.93899999999999995,"avg":2.0409999999999999,"max":3.3500000000000001},{"created_at":"2018-01-14 14:38:31","min":0.36699999999999999,"avg":0.39400000000000002,"max":0.42299999999999999},{"created_at":"2018-01-14 18:27:06","min":0.29699999999999999,"avg":0.44900000000000001,"max":0.90000000000000002},{"created_at":"2018-02-17 13:07:04","min":0.29499999999999998,"avg":0.30599999999999999,"max":0.34000000000000002},{"created_at":"2018-02-18 11:29:35","min":0.35999999999999999,"avg":0.38500000000000001,"max":0.40000000000000002}] 

Result in variable:

var test = {!! json_encode($test_min_max_list->toArray()) !!};

->

Array [length: 0]

How can I fix that and get an working array?

Answer 1

Try this:

 $test_min_max_list = TestsMinMax
    ::join('results', 'tests_min_max.id', '=', 'results.test_result_id')
    ->select('created_at','min','avg','max')
    ->where([
        ['results.user_id', '=', $user_id],
        ['results.test_id', '=', $request->get('test_id')],
    ])->get()->toArray();

In JS script

var array = {{ json_encode($test_min_max_list) }};
READ ALSO
OctoberCMS global page properties?

OctoberCMS global page properties?

Is it possible to set a series of global properties (such as social media usernames) that are available to all page views in OctoberCMS rather than having them associated to one CMS page or Static Page at a time?

69
Get all parents from a child

Get all parents from a child

Hellow, i have a simple table like:

52
Move Add To Cart button and Variation Selector above product short description in Woocommerce

Move Add To Cart button and Variation Selector above product short description in Woocommerce

How can I move Add To Cart button and Variation Selector above product short description (between price and short description) in Woocommerce product page?

67