Laravel pivot table attach duplicates many times

  laravel, laravel-7, php, pivot, pivot-table

In my project there’s a competition which includes many teams and an organizer can upload many documents/photos to a competition assigning to a team, so I decided to make a files table to store all the file data while there are separate tables for compactions and teams and I made a pivot table as competition_file with fields competition_id , team_id , file_id, and type as below image

enter image description here

Here’s how my UI looks like

enter image description here

In this form you’re able to upload multiple images/documents and the photos are uploaded by a Ajax request and the form gets the response uuid's of the images uploaded in the files table and submits again to the store functions in the documents table.

Here’s store function of the Files controller

 public function store(Request $request)
{
    $this->validate($request, [
        'file' => 'required|image',
    ]);

    $fh = new FileUploader($request);
    $fh->toDisk('public');

    if ($request->has('upload_dir')) {
        $fh->saveToDir($request->input('upload_dir', 'files'));
    }

    $result = $fh->upload();

    if ($result->isSuccessful()) {
        $file = new File([
            'key' => Uuid::generate(4),
            'name'=>$request->name,
            'description'=>$request->description,
            'allow_public_access' => false,
            'original_filename' => $result->getOriginalFilename(),
            'file_path' => $result->filePath(),
            'file_disk' => $result->diskName(),
            'file_url'  => $result->publicUrl(),
            'file_size_bytes' => $result->getFileSize(),
            'uploaded_by_user_id' => (auth()->id()) ?? auth()->id()
        ]);
        $file->category = $request->input('category', 'general');
        $file->save();

        return response()->apiSuccess([
            'uuid' => $file->uuid,
        ]);
    }

    return response()->apiError('Failed to upload file. Try with another file or contact admin.');
}

Here’s the relationship in the Teams modal

public function documents()
{
    return $this->belongsToMany(File::class,'competition_file')->wherePivot('type', 'image');
}

And here’s the store function of the documents controller

   public function store($competition, Request $request, Team $entity)
    {

    
    $uuid = $request->photos;
    File::whereIn('uuid', $uuid)->update(['name' => $request->name, 'description'=>$request->description]);        

     

     if ($request->has('photos') && is_array($request->photos)) {
        $files = $this->filesRepo->getByUuids($request->photos);

      

        if ($files->isNotEmpty()) {

           
            $entity->documents()->attach($files->pluck('id'),['team_id'=>$request->team,'competition_id'=>$competition]);
          

          
        }
    } }

i need to know what’s wrong with the pivot table, i was unable to use sync and i used attach and when i store the data to the and attach the relationships it duplicates if i have selected more than 1 image/document, as shown in the image below

enter image description here

while i have selected only 3 images i get duplicates’

here’s how the pivot table looks like after store

enter image description here

Somebody please help me out

Source: Laravel

Leave a Reply