Home > Enterprise >  Laravel livewire form won't allow only input from comments, requires both or image on its own
Laravel livewire form won't allow only input from comments, requires both or image on its own

Time:12-25

I am trying to input posts that let the user to input comments and/or image however my livewire component seems to be asking for the image to be included, because if no image is uploaded it doesn't seem to go through, if there is an image uploaded then the form will pass fine.

This is how the livewire component looks, with the form:

class PostForm extends Component
{



 use WithFileUploads;
    public $image;
        public $comments;
        public $post;


public function submit(){

    //dd($this);
    $this->validate([
        'image' => ['mimes:jpeg,bmp,png','required_without:comments'], // Only allow .jpg, .bmp and .png file types.
        'comments' => 'required_without:image',

    ]);

    $post = new Post();
    $post->user()->associate(Auth::user());
    $post->comments = $this->comments;

    //dd(isset($this->image));
    if (isset($this->image)==true) {

        $this->image->store('images', 'public');


        $post->image_path = $this->image->hashName();
    }
    $post->save();

    return redirect()->route('posts.index')
        ->with('success', 'post added');
}

public function render()
{
    return view('livewire.post-form');
}

This is how it looks in the livewire postform blade view:

<div>
{{-- If your happiness depends on money, you will never be happy with yourself. --}}

<form wire:submit.prevent="submit" enctype="multipart/form-data">

    @csrf

    <div >
        <label for="comments">Comments:</label>
        <textarea wire:model="comments"  id="comments" row="5" ></textarea>

        @error('comments')
        <div >{{$message}}</div>
        @enderror
    </div>
    <div >
        <input wire:model="image" id="image" type="file"  >

    </div>
    <button wire:click="submit" type="submit" >Create</button>
</form>

CodePudding user response:

More nullable validation criteria must be passed on since $image is specified by default as null.

 $this->validate([
    'image' => ['nullable','mimes:jpeg,bmp,png','required_without:comments'], // Only allow .jpg, .bmp and .png file types.
    'comments' => 'required_without:image',

]);

After that, if the picture is null or the user does not pick it, the validator does not validate the image.

  • Related