Laravel 查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24744825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:52:52  来源:igfitidea点击:

Laravel Queries Strings

urllaravellaravel-4query-stringlaravel-routing

提问by Melvin Koopmans

Does anyone know if it's possible to make use of URL query's within Laravel.

有谁知道是否可以在 Laravel 中使用 URL 查询。

Example

例子

I have the following route:

我有以下路线:

Route::get('/text', 'TextController@index');

And the text on that page is based on the following url query:

该页面上的文本基于以下 url 查询:

http://example.com/text?color={COLOR}

How would I approach this within Laravel?

我将如何在 Laravel 中解决这个问题?

回答by camelCase

For future visitors, I use the approach below for > 5.0. It utilizes Laravel's Requestclassand can help keep the business logic out of your routesand controller.

对于未来的访问者,我使用以下方法进行> 5.0. 它利用 Laravel 的Request,可以帮助将业务逻辑排除在您的routescontroller.

Example URL

示例网址

admin.website.com/get-grid-value?object=Foo&value=Bar

Routes.php

路由.php

Route::get('get-grid-value', 'YourController@getGridValue');

YourController.php

你的控制器.php

/**
 * $request is an array of data
 */
public function getGridValue(Request $request)
{
    // returns "Foo"
    $object = $request->query('object');

    // returns "Bar"
    $value = $request->query('value');

    // returns array of entire input query...can now use $query['value'], etc. to access data
    $query = $request->all();

    // Or to keep business logic out of controller, I use like:
    $n = new MyClass($request->all());
    $n->doSomething();
    $n->etc();
}

For more on retrieving inputs from the request object, read the docs.

有关从请求对象检索输入的更多信息,请阅读文档

回答by Kryten

Yes, it is possible. Try this:

对的,这是可能的。尝试这个:

Route::get('test', function(){
    return "<h1>" . Input::get("color") . "</h1>";
});

and call it by going to http://example.com/test?color=red.

并通过转到调用它http://example.com/test?color=red

You can, of course, extend it with additional arguments to your heart's content. Try this:

当然,您可以根据自己的喜好使用其他参数对其进行扩展。尝试这个:

Route::get('test', function(){
    return "<pre>" . print_r(Input::all(), true) . "</pre>";
});

and add some more arguments:

并添加更多参数:

http://example.com/?color=red&time=now&greeting=bonjour`

This will give you

这会给你

Array
(
    [color] => red
    [time] => now
    [greeting] => bonjour
)

回答by malhal

Query params are used like this:

查询参数的使用方式如下:

use Illuminate\Http\Request;

class ColorController extends BaseController{

    public function index(Request $request){
         $color = $request->query('color');
    }

回答by Joshua Oluikpe

public function fetchQuery(Request $request){
  $object = $request->query('object');
  $value = $request->query('value');
}