Riches
Riches

Reputation: 37

Laravel - passing php variable to JS as array

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?

Upvotes: 0

Views: 3061

Answers (2)

Riches
Riches

Reputation: 37

@ezw @It is all yours

I figured out what is the problem... I totally missed out that I'm passing:

['results.user_id', '=', $user_id],
['results.test_id', '=', $request->get('test_id')],

those data thru AJAX and I was running

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

this variable before that, thats why it was empty... Sorry for the confusion.

Upvotes: 0

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

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

Upvotes: 1

Related Questions