Create a record if it does not exist in the table or update data if the record exists

1

I need to save the data in a table if they do not already exist or update them if they exist. I have this code so far that you only create 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 runs every 5 minutes and has to check whether or not they exist in the table to be able to do the operations I mentioned above.

I'm occupying Laravel 5.6 Any ideas?

    
asked by Felipe 31.03.2018 в 23:47
source

1 answer

1

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 are the values that will be updated. In case the record does not exist, it will be created with the values provided in the first and second parameters.

As an example I will assume that with "name" we verify whether or not the record exists:

Coin::updateOrCreate(
    ['name' => $res->name],
    ['symbol' => $res->symbol, 'name' => $res->rank]
);

With this method you do not need to call the save () method.

For more information you can review the Eloquent documentation, in the Other creation methods section.

    
answered by 01.04.2018 / 01:11
source