F
Filament•15mo ago
Sugbo

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>
10 Replies
LeandroFerreira
LeandroFerreira•15mo ago
Did you include HasMedia and InteractsWithMedia in your model? Try:
//remove 'attachment' => $this->attachment,
foreach ($this->attachment as $file) {
$question->addMedia($file);
}
//remove 'attachment' => $this->attachment,
foreach ($this->attachment as $file) {
$question->addMedia($file);
}
and check in your media table
Sugbo
Sugbo•15mo ago
Yeah the model implements HasMedia and use InteractsWithMedia The code is not working. When I dd($this->attachment) its returning an empty array
LeandroFerreira
LeandroFerreira•15mo ago
can you share the whole code please?
Sugbo
Sugbo•15mo ago
Thats the whole code sir
LeandroFerreira
LeandroFerreira•15mo ago
extends Component ?
Sugbo
Sugbo•15mo ago
Yes. Its a livewire component
LeandroFerreira
LeandroFerreira•15mo ago
ahh ok I thought that you were using a custom filament page. The dd should show an array... 🤔 Can you run only this?
public function submit()
{
dd($this->attachment);
}
public function submit()
{
dd($this->attachment);
}
Sugbo
Sugbo•15mo ago
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
Dan Harrin
Dan Harrin•15mo ago
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”
LeandroFerreira
LeandroFerreira•15mo ago
Thank you Dan!