【问题标题】:PHP/Laravel, url with multiples argumentsPHP/Laravel,带有多个参数的 url
【发布时间】:2021-10-29 01:18:02
【问题描述】:

我正在构建一个 Laravel 应用,我需要使用如下所示的 URL:

/api/ads?page=Actuel&formatsQuery[]=side&formatsQuery[]=leaderboard&deviceQuery=mobile

我有 3 个参数(page、formatsQuery(作为数组)和 deviceQuery)。

您现在如何在路由和控制器中保存他以便在控制器的功能中具有正确的值?

我试过这个: 路线/api.php

//request to get ads for given parameters
Route::get('/ads', [MediaController::class, 'findAds']);

还有这个(MediaController.php):

public function findAds($page, $formatsQuery, $deviceQuery) {
      echo $page;
      if(sizeof($formatsQuery) <= 0 || sizeof($formatsQuery) > 3){
        return $this->unvalidParametersError();
      }
      //transform format to position depending on deviceQuery
      $position = [];
      $res = [];
      foreach ($formatsQuery as $format) {
        $res =  Media::where('position', $format)->inRandomOrder()->first()->union($res);
      }
      echo $res;
      return $res;
    }

然后我用这个测试它:

public function test_findAds()
    {
      $ads = Ad::factory()
            ->has(Media::factory()->count(3), 'medias')
            ->count(3)->create();
      $response = $this->get('/api/ads?page=Actuel&formatsQuery[]=side&formatsQuery[]=leaderboard&deviceQuery=mobile');

      $response->assertStatus(200);
    }

【问题讨论】:

  • 阅读documentation,这很容易解释...在您的情况下,您使用get 发送该URL(您应该这样做),所以您只需执行@987654327 @,它应该返回Actuel。用你所有的输入来做到这一点。对于数组,不要在名字后面写[]...
  • 你试过了吗?添加您的代码。您可以使用控制器中的 Request 对象读取查询。

标签: php laravel routes


【解决方案1】:

您正在使用GET 请求来获取您的数据。 GET 请求是一种在 URL 中发送参数的请求,在 URL 之后使用 ? 并用 &amp; 分隔参数。您可以在here 找到更多关于 HTTP 方法的信息。

在 laravel 中使用请求参数就是这么简单。首先,您需要像这样将Request $request 添加到您的方法原型中:

use Illuminate\Http\Request;

public function findAds(Request $request)

然后您可以简单地使用$request-&gt;parameter 来获取值。所以你需要像这样改变你的代码:

public function findAds(Request $request){
    $page = $request->page;
    $formatsQuery = $request->formatsQuery;
    $deviceQuery = $request->deviceQuery;

    // Your code
}

正如 @matiaslauriti 在 cmets 中提到的,您无需在 formatsQuery[] 之后放置 [] 即可在 GET 请求中发送数组。多次使用同一个键会自动为您创建一个数组。

【讨论】:

    猜你喜欢
    • 2018-02-21
    • 2020-08-14
    • 2015-04-02
    • 2019-03-11
    • 2012-11-06
    • 2015-10-06
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    相关资源
    最近更新 更多