Should I use the method createto insert a new record if it does not exist, and not update the record if it exists? Thanks.
create
Use the method for this firstOrCreate:
firstOrCreate
$user = User::firstOrCreate(['name' => 'John Doe']);
If you want to know if the user was created or selected, check the property wasRecentlyCreated:
wasRecentlyCreated
if ($user->wasRecentlyCreated) { // "firstOrCreate" didn't find the user in the DB, so it created it. } else { // "firstOrCreate" found the user in the DB and fetched it. }
In Laravel 5.2, you have a method updateOrCreatefrom Builder.php, it uses the method firstOrNewto check if the specified attributes exist in db and update records with given values or create and save new records.
updateOrCreate
firstOrNew
, updateOrCreate :
https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models
/** * Create or update a record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @return \Illuminate\Database\Eloquent\Model */ public function updateOrCreate(array $attributes, array $values = []) { $instance = $this->firstOrNew($attributes); $instance->fill($values)->save(); return $instance; }
Source: https://habr.com/ru/post/1617544/More articles:Extract words between double quotes in variable R - regexHow to get the type of array elements? - arraysAlt attribute for ASCII art in HTML? - htmlPython - paste to list - pythonReact / Redux: mapStateToProps does not display state in requisites - javascriptПреобразуйте столбец данных в 1 или 0 для значений "истина" / "ложь" и назначьте в dataframe - type-conversionUWP application as a wcf server? - .netThe website editor continues to modify the script and makes it useless - javascriptusing unicode in javascript - javascriptIs adding (or removing) an empty event listener no-op? - nullAll Articles