DEV Community

Arman Rahman
Arman Rahman

Posted on

Efficient Data Handling: Storing Items in Laravel Parent Tables Before Creating Parent Row

Some time we need to create items for the parent before creating the parent row creates. So you can use this formula for doing that action.

add a new column on your child table named temp_id . After that when you are going to store that item, do like this -

public function storeChildData(Request $request){
        $attribute = new ChildModel();
        $attribute->temp_id = rand(1111,9999); // Add a random value to the attribute
        ...
        ...
        $attribute->created_by = Auth::id();
        $attribute->save();

        // Store value on session as a array
        $tempArray = session('attributeTempId', []);
        $tempArray[] = $attribute->temp_id;
        session(['tempId' => $tempArray]);

       ...
       ...
    }
Enter fullscreen mode Exit fullscreen mode

Then go to your parent store method and add like this -

public function storeParentData(Request $request)

        $parent = new ParentModel;
        ...
        ...
        $parent->created_by = Auth::id();
        $parent->save();

        // Add this for update parent id on child
        ChildModel::whereIn('temp_id', session()->get('tempId'))->where('created_by', Auth::id())->update(['temp_id' => null, 'parent_id'=> $parent->id]);
        session()->flash('tempId');

        ...
        ...
    }
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs