Answer the question
In order to leave comments, you need to log in
How not to save record if id already exists in laravel?
foreach ($items as $item) {
$carObj = new Car();
$carObj->id = $item['id'];
$carObj->make = $item['make'];
$carObj->model = $item['model'];
$carObj->price = $item['price'];
$carObj->href = $item['href'];
$carObj->year = $item['year'];
$carObj->created = $item['created'];
$carObj->save();
}
Answer the question
In order to leave comments, you need to log in
How not to write a record if such id already exists?
try {
$carObj = new Car();
$carObj->id = $item['id'];
$carObj->make = $item['make'];
$carObj->model = $item['model'];
$carObj->price = $item['price'];
$carObj->href = $item['href'];
$carObj->year = $item['year'];
$carObj->created = $item['created'];
$carObj->save();
} catch (Illuminate\Database\QueryException $e) {
/* nothing */
}
Do you need to save the id? You don't have autoincrement in the database?
if ($car = Car::firstOrNew(['id' => $item['id']) and !$car->exists) {
$car->make = $item['make'];
...
$car->save();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question