【问题标题】:Laravel - How to pass variable as parameter to external API using guzzleLaravel - 如何使用 guzzle 将变量作为参数传递给外部 API
【发布时间】:2021-06-24 23:16:30
【问题描述】:

我正在使用 Laravel-5.8 和 Guzzle 来使用外部 api:

public  function index()
{
    try{
    $myparam = 'JKK123';
    $client = new Client();
    $res = $client->request('GET','https://examplet/tracking/$myparam', [
       'query' => ['key' => 'jkkffd091']
   ])->getBody();
    $geoLocation = json_decode($res->getContents(), true);
    $currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
        return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
    })->first();  

    $currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
    dd($currentLocationFilter);
    return view('index', [
        'currentLocation' => $currentLocation,
        'currentLocationFilter' => $currentLocationFilter,
        'geoLocation' => $geoLocation
    ]);
    }catch (Exception $exception) {
        Log::error($exception);
        return back();
    }
}

我正在尝试将变量作为参数传递给 API。我没有直接放它,因为它会改变。我只是尝试测试。

当我这样做时,如上面的代码所示

$res = $client->request('GET','https://examplet/tracking/$myparam', [ ...

然后

dd($currentLocationFilter);

我明白了:

array:1 [▼
 0 => ""
]

但是当我直接放值的时候,

$res = $client->request('GET','https://examplet/tracking/JKK123', [

我得到了所需的结果:

 array:2 [▼
  0 => "2.1234565432145"
  1 => "1.7864321249555"
]

如何将变量作为参数传入外部 API?

谢谢

【问题讨论】:

    标签: laravel api guzzle


    【解决方案1】:

    像这样使用double quotes for executing variable

    $res = $client->request('GET',"https://examplet/tracking/{$myparam}", [...
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2015-08-24
      相关资源
      最近更新 更多