Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ripper's avatar

Laravel adding new record in database automatically

I have two tables tableA and tableB. The tableA has many relation with tableB. So when I make ajax request from frontend which is build in vuejs. This code has been executed on backend

if (!$object instanceof TableA) { $object = $this->getById($object); }

    $object->title = strip_tags($request->title);
    $object->description = strip_tags($request->description);
    $object->gender = $request->gender;
    $object->age_range_id = $request->age_range;

    $object->user_id = $request->user()->id;
    $object->status = TableA::STATUS_PENDING;
    $object->deadline = now()->addMinutes(Config::getDeadlineMinutes());

    if ($request->time != null && $request->time != 'null') {
        $object->time = $request->time;
    }
    if ($object->save()) {
        if ($request->event_types) {
            $object->types()->sync($request->event_types);
        }
        if ($request->outfit_styles) {
            $object->styles()->sync($request->outfit_styles);
        }
        if ($request->dress_code != null && $request->dress_code != 'null') {
            $object->codes()->sync([$request->dress_code]);
        }

        /** @var User $user */
        $user = $request->user();
        // If user outfit is 2 (allow next outfit)
        if ($user->add_outfit_status == User::ADD_STATUS_ALLOW_NEXT) {
            $user->add_outfit_status = User::ADD_STATUS_NEUTRAL;
            $user->save();
        }
    }

This is the code in repository. When $object->save(); is called it automatically creates a new record in tableB. The record has some random values in it. The function to store values in tableB is different and I dd before that and still the $object->save(); creates 2 - 3 records in the database with relation to tableA. So my question is why this is happening and how I can solve that ?

0 likes
3 replies
PovilasKorop's avatar

Maybe there is some Observer class with created() method for TableA model?

ripper's avatar

@PovilasKorop I search for observer and I don't find any observer. The point to notice here this issue happens randomly sometimes it works fine and sometimes it didn't. One more thing the actual tableB entries start with id 3300 and randomly entries have id of 1221.

PovilasKorop's avatar

@ripper sorry I don't think it's possible to solve your issue by "blind guessing", without actually debugging the situation

1 like

Please or to participate in this conversation.