我正在构建一个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']);
and this (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方法的信息。
在laravel中使用请求参数是如此简单。首先,您需要将Request $request
添加到方法原型中,如下所示:
use IlluminateHttpRequest;
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
请求中的数组。多次使用相同的键会自动为您创建一个数组。