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>