Laravel 5.4 - 根据用户请求订购数据

时间:2018-02-09 02:37:30

标签: php database laravel laravel-5 laravel-5.4

我想从表中创建一个报表,其数据可以根据用户的请求进行排序,我试试如下

suppliers.blade.php

<form id="print" method="POST" action="/admin/suppliers/report" target="blank">
{{ csrf_field() }}
<div class="input-field">
    <select name="orderBy">
        <option value="" disabled selected>Order by</option>
        <option value="'id', 'asc'">Id (Asc)</option>
        <option value="'id', 'desc'">Id (Desc)</option>
        <option value="'name', 'asc'">Name (A - Z)</option>
        <option value="'name', 'desc'">Name (Z - A)</option>
        <option value="'updated_at', 'asc'">Date (Asc)</option>
        <option value="'updated_at', 'desc'">Date (Desc)</option>
    </select>
    <label>Order by</label>
 </div>
<button type="submit" class="btn-flat">print</button>

路线

Route::post('/admin/suppliers/report', 'ReportController@supplier');

ReportController.php

public function supplier(Request $request)
{
$orderBy = request('orderBy');

$suppliers = Supplier::orderBy($orderBy)->get();

$pdf = PDF::loadView('report.suppliers', compact('suppliers'));

return $suppliers;
// return $pdf->setPaper('a4')->stream('suppliers.pdf');
}

我尝试按Id(Desc)和Name(Z - A)排序,但结果总是按Id(Asc)排序,如下所示

[
{
    "id": 1,
    "name": "Supplier 1",
    "phone": "1111111111",
    "address": "Jl. 1",
    "created_at": "2018-01-27 11:21:35",
    "updated_at": "2018-01-27 11:21:35"
},
{
    "id": 2,
    "name": "Supplier 2",
    "phone": "2222222222",
    "address": "Jl. 2",
    "created_at": "2018-01-27 11:21:56",
    "updated_at": "2018-01-27 11:21:56"
},
{
    "id": 3,
    "name": "Supplier 3",
    "phone": "3333333333",
    "address": "Jl. 3",
    "created_at": "2018-01-27 11:22:24",
    "updated_at": "2018-01-27 11:22:24"
}
]

1 个答案:

答案 0 :(得分:2)

$orderBy = request('orderBy');

仍然会以"'id', 'desc'"

结果

你要做的是

'移除"'id', 'asc'"成为"id,asc"

然后,在ReportController

$orderBy = request('orderBy');
$orderBy = explode(',', $orderBy);
$suppliers = Supplier::orderBy($orderBy[0], $orderBy[1])->get();