Open sidebar
//This is the controller's method: public function create($id=null) { if($id) { $station = $this->api->getITem('station', $id); } $cities = $this->api->get('city', [], ['country' => '59302eb0cae21503ebeb5bcb']); $cities = $cities['_items']; return view('station.create', compact('cities', 'station')); } ////This is the bridge between API and Laravel Application. namespace App; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class ApiBridge { public $client; public function __construct() { $this->client = new Client([ 'base_uri' => 'some_address_here'; ]); } public function get($endpoint, $embed=[], $where=null) { $embedded = array_fill_keys($embed, 1); $embedded = json_encode($embedded); $wherefix = null; if ($where) { foreach ($where as $k => $v) { $wherefix .= $k . '==' . $v . ','; } $wherefix = rtrim($wherefix, ",").'&'; $endpoint = $endpoint.'?where='.$wherefix; } if(count($embed) > 0) { $endpoint = $endpoint.'&embedded='.$embedded; } $response = $this->client->request('GET', $endpoint); return json_decode($response->getBody(), true); } public function getItem($endpoint, $id) { try{ $response =$this->client->request('GET', $endpoint.'/'. $id); return json_decode($response->getBody(), true); }catch(RequestException $e){ $err = json_decode($e->getResponse()->getBody()->getContents(), true); $response['error'] = $err['_error']; return $response; } } public function create($endpoint, $request) { try{$response = $this->client->request('POST', $endpoint, ['json' => $request]); return json_decode($response->getBody()->getContents(), true); }catch(RequestException $e) { $err = json_decode($e->getResponse()->getBody()->getContents(), true); $response['error'] = $err['_issues']; return $response; } } public function edit($endpoint, $request) { try{ $response = $this->client->request('PATCH', $endpoint, ['json' => $request]); }catch(RequestException $e) { return json_decode($e->getResponse()->getBody()->getContents(), true); } } public function delete($endpoint, $id) { try{ $response =$this->client->request('DELETE', $endpoint.'/'. $id); }catch(RequestException $e){ $err = json_decode($e->getResponse()->getBody()->getContents(), true); $response['error'] = $err['_error']; return $response; } } }
Close sidebar
Back
Please note that all pasted data is publicly available.
X (fomerly Twitter)
GitHub
Use setting
Back
Please note that all pasted data is publicly available.
X (fomerly Twitter)
GitHub
Use setting