使用 livewire 上传多张图片

Uploading multiple images with livewire

我正在使用 livewire,我正在尝试为 post 上传多张图片。但是,我无法让它工作。当我用图像创建 post 时,没有图像保存到数据库中

class Add extends Component
{
    use WithFileUploads;
    public $post;
    public $users;
    public $body;
   
    public $image = [];
  
    public $title;
    public $category = 1;

    protected $rules = [
        'category' => 'required|integer|exists:categories,id',
        'title' => 'required|min:4',
        'body' => 'required|min:4',
    ];

    public function createPost()
    {
        if (auth()->check()) {
            $this->validate();
            $post = Post::create([
                'user_id' => auth()->user()->id,
                'title' => $this->title,
                'category_id' => $this->category,
                'status_id' => $this->status,
                'body' => $this->body,
       
            ]);
                foreach ($this->image as $photo) {
                   $photo->storeAs('posts', str::random(6));
                 }
                $post->save();
                session()->flash("message", "Featured image successfully uploaded");

用于存储多张图片:

foreach ($this->photos as $photo) {
     $file_name = uniqid().$poto->extension();// or any name you want
     $photo->storeAs('posts',$file_name);
}

您可以使用文档获取更多信息:https://laravel-livewire.com/docs/2.x/file-uploads#multiple-files

P.S:当你使用 Post::create 时,你不需要 $post->save,并在你的路由中使用 auth 中间件。