LadyDeathKZN's avatar

Pivot table with extra fields

I have a pivot table that gets populated by another controller. It has: user_id, team_form_id, file_upload.

The user_id and file_upload gets populated by another controller. I need to get the team_form_id populated by a form that is submitted. The user uploads multiple files and it gets stored, the person then submits the form - I have had to use 2 controllers as the uploads are chunked.

I would like to check where the user_id is = to Auth::user()->id and where the team_form_id is null to be populated with the form id that is being submitted:

public function store(Request $request)
    {
        $teamform = new TeamForm;
        $teamform->team_form_id = $request->team_form_id;
        $teamform->teamupload = $request->teamupload;
        $teamform->user_id = Auth::user()->id;

        $teamform->save();

        if ($teamform->save()) {
            $teamuser = Auth::user()->id;
            $teamform->teamlog()->sync($teamuser);
        }

        return redirect(route('team-form.index'))->with('success', 'Form added successfully');
    }

The model for the file upload is TeamFormFIle. I have tried the below:



        if ($teamform->save()) {
            $files = TeamFormFile::find('user_id' == Auth::user()->id);
            if ($files->team_form_id == null) {
                foreach($files as $file) {
                    $file->team_form_id = $teamform->id;
                    $file->save();
                }
            }
        }

So basically loop through the records find the user that is currently logged in and submit the form id to the team_form_id that are null.

0 likes
1 reply
bobbybouwmann's avatar
Level 88

The problem is in this line

$files = TeamFormFile::find('user_id' == Auth::user()->id);

This bit 'user_id' == Auth::user()->id will return true or false because of the double ==. Instead you need to do this

$files = TeamFormFile::where('user_id', Auth::user()->id)->first();

$files can be null here is so you should check for that as well before you go into the if.

Also your code is a bit of a mess! Find or first always returns one item or null. So you're if will be alright, but after that you're looping over a single item, that's not possible...

Please or to participate in this conversation.