SPL3S
8 months ago

Store current(future?) entry ID

Posted 8 months ago by SPL3S

I'm sure there is a much smarter method to do this but my brain can't think of one, as I'm still learning basics...

And if you have a smarter easier method, please correct me.

I have a form where the user selects options and then selects multiple names. Options are stored to the table "categoryAge". Names are stored to "categoryAgeAthletes" table in order to keep each entry in separate rows so it's easier to edit for the user. I can store the data, but I can't figure how to get ID of the "categoryAge" entry in "categoryAgeAthletes" to keep track of it. I tried to use ['categoryAge_id' => $categoryAge->id] in for each loop, but it doesn't work as logically that ID doesn't exist at the time of the store function.

public function store(Event $event, CategoryAge $categoryAge)
    {
        
        $attributes = request()->validate([
            'ageGroup' => ['required', 'min:3'],
            'competitionCategory' => ['required', 'min:2'],
            'music' => ['required', 'min:4'],
            'nthCategory' => ['required', 'min:1']
        ]);

        //get multiple or single selected names
        $athleteNames = request('surnameName');
    
        categoryAge::create(
            $attributes + 
            ['event_id' => $event->id] + 
            ['user_id' => auth()->id()]
        );

        //store athletes names to categoryAgeAthletes table
        foreach ($athleteNames as $athleteName) {
           $data = new categoryAgeAthletes(
            ['surnameName' => $athleteName] +
            ['categoryAge_id' => $categoryAge->id] +
            ['user_id' => auth()->id()]
        );

           $data->save();
       }
        
        return back();  
    }

Please sign in or create an account to participate in this conversation.