简体   繁体   中英

append to url in Laravel

I'm trying to implement a displayPerPage (10, 25, 50, etc.) when displaying a list of results on an index page. However i'm having a hard time how to just append that to the url without replacing the other query strings.

Example:

I have a paginator to switch pages however, if i'm on page 5 for example and select display per page 10 results on my select dropdown, it will load the results but erase the page=5 from the url. How to I just append displayPerPage without erasing where I currently am on the paginator.

Thanks for any help.

I know its possible to do it without creating a custom paginator since I have done it on another project with laravel 4, but that was a while back and I can't seem to figure out how to do it again.

Assuming $objects is the list of the item you're paginating, on your view you can add your paginator like that:

{{$objects->appends(request()->query())->links()}}

and query strings like your requestPerPage will be carried

After battling with this issue, I wrote a url parser helper function in php to to find and replace certain things in url after the ? sign (query part)

//for displayPerPage, orderBy and sortBy parse the url and replace with new values

function urlQueryParse($queryToReplace, $newValue){

//    extract query from url
$fullUrl = Request::fullUrl();

if(strpos($fullUrl, '?') !== false){

    //find everything after the ? in url
    $url = substr($fullUrl, strpos($fullUrl, "?") + 1);

//        check url to make sure $queryToReplace exists in the url

if(strpos($url, $queryToReplace) !== false) {

//        look through the remaining url query and replace whats given to the function
        $newUrL = preg_replace('/('. $queryToReplace. '\=)([^&]+)/', $queryToReplace.'='.$newValue, $url);

        return Request::url()."?{$newUrL}";
    }

//        if the ? exists but the queryToReplace is not in the url, then add it to the query string
    return Request::url()."?{$url}&{$queryToReplace}={$newValue}";

}
//if the url doesnt have ? sign then simply insert the new value
return Request::url()."?{$queryToReplace}={$newValue}";


}

Hopefully this helps someone. If you have any ides of how to improve it, I'm open to suggestions.

PS I'm working on Laravel 5.2

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