Z
Z
Zhandev2016-07-09 15:29:39
MySQL
Zhandev, 2016-07-09 15:29:39

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();
        }

How not to write a record if such id already exists?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Alekhin, 2016-07-09
@Zhandev

How not to write a record if such id already exists?

Make a try catch
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 */
}

This way we catch the exception and just skip it. An error in this case will not stop the script.

Z
Zhandev, 2016-07-09
@Zhandev

At the moment, if id exists, then an error is displayed

S
Skrolea, 2016-07-09
@Skrolea

Do you need to save the id? You don't have autoincrement in the database?

S
Sergey Semenko, 2016-07-09
@abler98

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 question

Ask a Question

731 491 924 answers to any question