Carosobin's avatar

member function getFirstMediaUrl() on null

trying to upload an image using spatie libray an i am getting this error

`member function getFirstMediaUrl() on null`

class Create extends Component
{
    use WithFileUploads;

    public $thread;
    public $users;
    public $body;
    public $image;

    public $photo;
    public $title;
    public $space = 1;
    protected $rules = [
        'space' => 'required|integer|exists:spaces,id',
        'title' => 'required|min:4',
        'body' => 'required|min:4',
        'image' => ['required', 'image'],
    ];

    public function createThread()
    {
        if (auth()->check()) {
            $this->validate();
            $thread = Thread::create([
                'user_id' => auth()->user()->id,
                'title' => $this->title,
                'space_id' => $this->space,
                'body' => $this->body,

            ]);
  
            $this->image = $this->thread->getFirstMediaUrl('thread_image');
            $this->thread->clearMediaCollection('thread_image');
            $this->thread->addMedia($this->image->getRealPath())->toMediaCollection('thread_image');

            session()->flash("message", "Featured image successfully uploaded");


            session()->flash('success', 'Post was added successfully!');
            return redirect(route('index'));
            $this->reset();
        }

        abort(Response::HTTP_FORBIDDEN);
    }
    public function render()
    {
        $spaces = Space::get();
        return view('livewire.thread.create',[
            'spaces' => $spaces,
        ]);
    }
}
0 likes
1 reply
tjanuki's avatar

Hi @carosobin , the error message means that you created a thread in the wrong variable.

Instead of $thread = Thread::create , try $this->thread = Thread::create .

Please or to participate in this conversation.