PHP/Laravel、url 有多个参数

PHP/Laravel, url with multiples arguments

我正在构建一个 Laravel 应用程序,我需要使用一个看起来像这样的 URL :

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

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

你现在知道如何在路由和控制器中保存他,以便在控制器的功能中获得正确的值吗?

我试过这个: routes/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);
    }

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

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

use Illuminate\Http\Request;

public function findAds(Request $request)

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

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

    // Your code
}

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