【问题标题】:Laravel livewire form won't allow only input from comments, requires both or image on its ownLaravel livewire 表单不允许只输入评论,需要两者或图像本身
【发布时间】:2022-01-24 18:37:28
【问题描述】:

我正在尝试输入允许用户输入 cmets 和/或图像的帖子,但是我的 livewire 组件似乎要求包含图像,因为如果没有上传图像,它似乎不会通过,如果上传了图片,则表单将通过。

livewire 组件的外观如下:

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');
}

这是它在 livewire postform 刀片视图中的外观:

<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 class=" my-10">
        <label for="comments">Comments:</label>
        <textarea wire:model="comments"  id="comments" row="5" class=" p-2 bg-gray-200 @error('comments') is-invalid @enderror"></textarea>

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

    </div>
    <button wire:click="submit" type="submit" class="btn btn-blue">Create</button>
</form>

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    更多 nullable 验证条件必须传递,因为 $image 默认指定为 null。

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

    之后,如果图片为空或者用户没有选择,验证器不验证图片。

    【讨论】:

    • 非常感谢,哦,好吧,既然图像被声明为空,需要给它一个允许它可以为空的规则
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2021-05-16
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多