Laravel route url with query string

后端 未结 4 522
感动是毒
感动是毒 2021-02-02 07:59

On laravel 4 I could generate a url with query strings using the route() helper. But on 4.1 instead of:

$url = url(\'admin.events\', array(\'lang\' => \'en\')         


        
4条回答
  •  我在风中等你
    2021-02-02 08:30

    Laravel's route() and action() helper methods support URL params. The url() helper method, unfortunately does not.

    Simply provide an array with key values to the route parameters. For example:

    route('products.index', ['manufacturer' => 'Samsung']);
    
    // Returns 'http://localhost/products?manufacturer=Samsung'
    

    You can also still include your route parameters (such as ID's and models) to accompany these parameters:

    route('products.show', [$product->id, 'model' => 'T9X']);
    
    // Returns 'http://localhost/products/1?model=T9X'
    

    This is also supported in action methods:

    action('ProductController@index', ['manufacturer' => 'Samsung']);
    

    You can also supply query parameters inside the link_to_route() and link_to_action() methods:

    link_to_route('products.index', 'Products by Samsung', ['model' => 'Samsung');
    
    link_to_action('ProductController@index', 'Products by Samsung', ['model' => 'Samsung']);
    

    2019 - EDIT:

    If you don't have route names, or don't like using action(), simply use:

    url('/products?').\Illuminate\Support\Arr::query(['manufacturer' => 'Samsung']);
    
    // Returns 'http://localhost/products?manufacturer=Samsung'
    

    Or:

    url('/products?').http_build_query(['manufacturer' => 'Samsung'], null, '&', PHP_QUERY_RFC3986);
    
    // Returns 'http://localhost/products?manufacturer=Samsung'
    

    Or create a simple helper function:

    use Illuminate\Support\Arr;
    use Illuminate\Support\Str;
    
    function url_query($to, array $params = [], array $additional = []) {
        return Str::finish(url($to, $additional), '?') . Arr::query($params);
    }
    

    Then call it:

    url_query('products', ['manufacturer' => 'Samsung']);
    
    // Returns 'http://localhost/products?manufacturer=Samsung'
    
    url_query('products', ['manufacturer' => 'Samsung'], [$product->id]);
    
    // Returns 'http://localhost/products/1?manufacturer=Samsung'
    

提交回复
热议问题