I need to save the data in a table if it doesn't exist yet or update it if it does exist. I have this code so far that only creates them in the table, the table is called Coin.php
$client = new Client([
'base_uri' => 'https://api.coinmarketcap.com/v1/',
'timeout' => 2.0,
]);
$response = $client->request('GET', 'ticker');
$coins = json_decode($response->getBody()->getContents());
foreach ($coins as $res) {
$datos = new Coin;
$datos->name = $res->name;
$datos->symbol = $res->symbol;
$datos->rank = $res->rank;
$datos->save();
}
This method is a command that is executed every 5 minutes and has to check if they exist or not in the table to be able to do the operations that I mentioned above.
I'm running Laravel 5.6 Any ideas?
If you need to create a record or update it, you can use updateOrCreate(), whose first parameter is the values with which you check if the record exists or not, and the second parameter is the values that will be updated. If the record does not exist, it will be created with the values provided in the first and second parameters.
As an example I am going to suppose that with "name" we verify if the record exists or not:
With this method you don't need to call the save() method.
For more information you can review the Eloquent documentation, in the Other creation methods section.