简体   繁体   中英

How To Pass Array in Php Curl GET request -Laravel?

i wanted to take an array of courseIds as input at the endpoint like "courseId":[14,15] .So, i added an extra [] in $Params .I tried as in the below code. it returns null from the endpoint. i think my curl url is not correct. How can i fix this? Any Help Is much appreciated.

the curl Url looks like this - http://127.0.0.1:8000/api/tutorByCourse?courseId%5B0%5D=14%2C15

$Params = ['courseId' => [$myCourse]];
dd($Params);
$curlConfig = array(
         CURLOPT_URL            => $url . "/api/tutorByCourse" ."?".http_build_query($Params),
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_RETURNTRANSFER => true,
        );

Curl Endpoint

public function getTutorByCourseId(Request $request)
    {
      $validator = Validator::make(
            $request->all(),
            [
                'courseId'     => 'required|array',
            ]
        );
}

dd($myCourse) shows "14,15" .

dd($Params) shows

array:1 [
  "courseId" => array:1 [
    0 => "14,15"
  ]
]

I also tried like below:


$Params=explode(',',$myCourse);

$delimeter = '?';

foreach ($Params as $v) {
  $queryParams .= "$delimeter"."courseId=$v";
  $delimeter = '&';
}

CURLOPT_URL            => $url . "/api/tutorByCourse" .$queryParams,

then, the url look like this - http://127.0.0.1:8000/api/tutorByCourse?courseId=14&courseId=15

this too returns null from the endpoint

I think you already have your answer, take a look:

$Params = ['courseId' => [$myCourse]];

dd($myCourse) shows "14,15".

I don't think you're saving your courseId correctly, because it appears $myCourse is a literal string of "14,15" rather than an array [14, 15]. http_build_query can handle arrays (it doesn't need converted into a string first).

Do the following:

$myCourse = [14, 15]; // Or however this array is populated with IDs, this is just an example.
$parameters = ['courseId' => $myCourse];

Then build the query with the new $parameters.

Additional note: Your endpoint will continue to return "null" until getTutorByCourseId() returns a response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM