简体   繁体   中英

Laravel 5 Pagination sort by from user input

i want an option for the user to sort the pagination from either in ascending or descending order. i tried the code below but i dont know how to insert the selected value.

index.blade.php

   <select name="orderby" id="orderby">
                <option value="asc">Ascending</option>
                <option value="desc">Descending</option>
            </select>

    {!! $finding_tbl->appends(['sort' => 'here'])->render() !!}

here is my index in PagesController

 public function index()
    {
        $sort =$_GET['sort'];
        $finding_tbl = findings::orderBy('id', $sort)->paginate(5);
        $finding_tbl->setPath('home');
        return view('pages.index',compact('finding_tbl','sort') );
    }

The recommended method to access your get variable (if your using Laravel 5) is to obtain an instance of the request via dependency injection. To quote the documentation :

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\\Http\\Request class on your controller constructor or method.

In your case, your controller would look something like this.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class PagesController extends Controller
{

    public function index(Request $request)
    {
        $sort = $request->input('sort', 'asc');
        $finding_tbl = findings::orderBy('id', $sort)->paginate(5);
        $finding_tbl->setPath('home');
        return view('pages.index',compact('finding_tbl','sort') );
    }
}

Once you have an instance you can access any input variables (GET/POST) like so:

$sort = $request->input('sort');

If you need to define a default value for when the variable doesn't exist this can be passed as the second parameter.

$sort = $request->input('sort', 'asc');

I use asc as the default value for sorting.

In your view:

{!! $finding_tbl->appends(['sort' => Input::get('sort', 'asc')])->render() !!}

In your controller, use Laravel $request instance or Input facade to get the query string parameters instead of the global array.

$sort = Input::get('sort', 'asc');

Or (when you use dependency injection)

public function index(Request $request) {
    # ...
    $sort = $request->get('sort', 'asc');
    # ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM