Ad

Laravel FirstOrCreate Not Working Properly?

- 1 answer

I am importing some data with the foursquare api. My database contains multiple foursquare_id duplicates. Am I doing something wrong with the code here?

I thought the way this is set up it will check the database for the column value of foursquare_id?

Bar::firstOrCreate([
    // do not check for these 2 below because they are mandatory
    'foursquare_id' => $item['venue']['id'],
    'name' => $item['venue']['name'],
    'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '',
    'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',
]);
Ad

Answer

That's right. You only receive the 'first' if all elements of your passed array exist in the row object.

The alternative is using firstOrNew:

$foo = Bar::firstOrNew(['foursquare_id' => $item['venue']['id']]); // find the object with this foursquare_id. Nothing found? Create a new one with the given foursquare_id
$foo->name = $item['venue']['name'];
$foo->postalCode = isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '';
$foo->city = isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '';
$foo->save();
Ad
source: stackoverflow.com
Ad