jeudi 8 février 2018

Laravel 5.4 - order data based on user request

I want to create a report from a table whose data can be ordered based on request from the user, I try as below

suppliers.blade.php

<form id="print" method="POST" action="/admin/suppliers/report" target="blank">

<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

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

I try to order by Id (Desc) and by Name (Z - A), but the result is always ordered by Id (Asc), as below

[
{
    "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"
}
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire