Created
April 19, 2023 11:11
-
-
Save Shahinyanm/bc72c8b41deb69f2f619ae7613ea8a25 to your computer and use it in GitHub Desktop.
Command to fetch and update currencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Console\Commands; | |
| use App\Models\Currency; | |
| use Illuminate\Console\Command; | |
| use Illuminate\Support\Facades\Http; | |
| /** | |
| * | |
| */ | |
| class UpdateCurrencies extends Command | |
| { | |
| /** | |
| * The name and signature of the console command. | |
| * | |
| * @var string | |
| */ | |
| protected $signature = 'update:currencies'; | |
| /** | |
| * The console command description. | |
| * | |
| * @var string | |
| */ | |
| protected $description = 'Update Currencies one time in a day'; | |
| /** | |
| * Create a new command instance. | |
| * | |
| * @return void | |
| */ | |
| public function __construct() | |
| { | |
| parent::__construct(); | |
| } | |
| /** | |
| * Execute the console command. | |
| * | |
| * @return void | |
| */ | |
| public function handle(): void | |
| { | |
| $response = $this->fetchCurrencies(); | |
| $this->updateRates($response->rates, $response->base); | |
| } | |
| /** | |
| * @return mixed | |
| */ | |
| private function fetchCurrencies(): mixed | |
| { | |
| $baseCurrency = config('currency.base_currency'); | |
| $currencies = Http::get('http://api.exchangeratesapi.io/v1/latest?access_key=d7f984291df38e362e65b1c4d4030cd0&format=1&base='.$baseCurrency); | |
| return json_decode($currencies->body()); | |
| } | |
| private function updateRates($rates, $base) | |
| { | |
| $currency = Currency::query()->firstOrCreate(['currency' => $base]); | |
| $currency->rates = $rates; | |
| $currency->save(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment