Passing parameter in Eloquent ORM inside a javascr

2019-07-14 17:09发布

问题:

I have a Laravel app where i'm using jQuery DataTables Master/Details to show some extra information. I can show the data to the child row, but I want it filtered first, depending on the row selected. The information that i want to retrieve is not on the original data source which I used to create the DataTable. Therefore i want to pass the record id to the new query that I am using directly from the javascript. Here is the code:

function kpi_values(d) {
    // `d` is the original data object for the row
    var $id = d.id;
    return '<table>'+
                '<thead>'+
                    '<tr>'+
                        '<th>Month</th>'+
                        '<th>Value</th>'+
                        '<th>Comment</th>'+
                    '</tr>'+
                '</thead>'+
                '<tbody>'+
                    '@foreach( \App\Reports::with("kpi")
                                            ->where("kpi_id",'+$id+')'+ 
                                            //this gives no records
                                            //->where("kpi_id",$id) -> this gives an error
                                            '->orderBy("month","desc")
                                            ->take(5)
                                            ->get() as $report)'+
                    '<tr>'+
                        '<td>{{$report->month}}</td>'+
                        '<td>{{$report->value}}</td>'+
                        '<td>{{$report->comment}}</td>'+
                    '</tr>'+
                    '@endforeach'+
                '<tbody>'+
            '</table>'
}

The error that I receive is:

ErrorException in e09c19f3dff5443f7b05b7c3c3e2f2a2 line 66:
Undefined variable: id

EDIT 1 I just realised that var $id is not a php variable therefore it will not work like that. So I updated my code by replacing var $id = d.id with <?php $id = /*the problem*/ ?>

however I cannot pass the d.id as a value to that variable.

回答1:

I think you can't not get an id from javascript to PHP like that. Because PHP render your script and send it with HTML into browser.

You should write ajax call for each row or prepare data before render into HTML



回答2:

This won't work the way you would like. You are better going with your original approach. If you post you db structure on your previous question I can take a look at it.