File Attachment Does Not Exist on Media Library Plugin/Form Builder
Hi,
I don't understand why I get "File Attachment Does Not Exist" . I am using Spatie Media Library Plugin for a file upload. I am using it not in the admin panel
This is the Livewire Class Component:
public $title ;
public $attachment;
public function render() { return view('livewire.post-question'); } public function mount(): void { $this->form->fill(); } protected function getFormSchema(): array { return [ TextInput::make('title')->required(),
SpatieMediaLibraryFileUpload::make('attachment'),
// ... ]; }
public function create(): void { Question::create($this->form->getState()); } public function submit() { $question = Question::create([ 'title' => $this -> title, 'attachment' => $this->attachment,
]); $question -> addMedia('attachment') -> toMediaCollection(); } This is the Livewire View Component: <div> <form wire:submit.prevent="submit"> {{ $this->form }}
<button type="submit" > Submit </button>
</form> </div>
public function render() { return view('livewire.post-question'); } public function mount(): void { $this->form->fill(); } protected function getFormSchema(): array { return [ TextInput::make('title')->required(),
SpatieMediaLibraryFileUpload::make('attachment'),
// ... ]; }
public function create(): void { Question::create($this->form->getState()); } public function submit() { $question = Question::create([ 'title' => $this -> title, 'attachment' => $this->attachment,
]); $question -> addMedia('attachment') -> toMediaCollection(); } This is the Livewire View Component: <div> <form wire:submit.prevent="submit"> {{ $this->form }}
<button type="submit" > Submit </button>
</form> </div>
10 Replies
Did you include HasMedia and InteractsWithMedia in your model?
Try:
and check in your media table
Yeah the model implements HasMedia and use InteractsWithMedia
The code is not working. When I dd($this->attachment) its returning an empty array
can you share the whole code please?
Thats the whole code sir
extends Component ?
Yes. Its a livewire component
ahh ok
I thought that you were using a custom filament page.
The dd should show an array... 🤔
Can you run only this?
Its working now Sir. This one actually works foreach ($this->attachment as $file) {
$question->addMedia($file);
}
But I have to add toMediaCollection()
Appreciate the help
TYSM
This dd($this->attachment) will return an array
that is not quite correct
you should not be using $this to access form data directly
getState() should be used only.
you are not calling $this->form->model($model)->saveRelationships() which is why it isnt saving
its in the docs “field relationships”
Thank you Dan!