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

Greg123's avatar
Level 13

Attaching Existing Uploaded files When Creating a Post

I'm trying to attach multiple files (pdf's) already in the db (through ui - dropdown list with checkbox) to a post when creating the post. The post itself is saving, but no relationship record is saved to the file_post pivot table. Both the File and Post model return a belongsToMany relationship. I think the primary issues has to do with trying to attach files to an array ($data) and not an object. Thanks for the help!

public function store(Requests\PostStoreRequest $request) {

    $data = $this->handleRequest($request);

    Post::create($data);


    if($request->hasFile('file'))
    {
        $files = $request->file('file');

        $this->files()->attach($files);

    }


    return redirect('admin/posts')->with('message','New post successfully created!');

}

Schema::create('file_post', function (Blueprint $table) { $table->primary('file_id', 'post_id'); $table->unsignedBigInteger('file_id'); $table->unsignedBigInteger('post_id'); $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade'); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->timestamps(); });

Form

            <div class="">
                <label class="text-sm w-full text-indigo-700 font-semibold" for="file">Files</label>
                 @foreach($files as $file)
                    <div class="flex items-center">
                        <input class="mr-3" type="checkbox" name="file[]" value="{{ $file->id }}" multiple/>
                        <label>{{ $file->name }}
                    </div>
                 @endforeach
            </div>
            <p class="py-1 text-red-500">@error('file[]') {{ $message }} @enderror </p>
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

It is not a file input type, so:

$post = Post::create($data);

//if($request->hasFile('file'))
//{
//    $files = $request->file('file');
    $post->files()->attach($request->input('files', []));
//}

This assumes that Post model has a belongsToMany files relationship defined

Greg123's avatar
Level 13

Thanks for the help. Solved. The issue was the input "type" you pointed out. I appreciate your help!!

Please or to participate in this conversation.