【问题标题】:Uploading multiple images with livewire使用 livewire 上传多张图片
【发布时间】:2022-01-16 08:53:18
【问题描述】:

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

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");

【问题讨论】:

    标签: php laravel laravel-livewire


    【解决方案1】:

    用于存储多张图片:

    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 中间件。

    【讨论】:

    • 我收到这个错误数组到字符串的转换
    猜你喜欢
    • 2017-04-08
    • 2014-03-19
    • 2011-12-10
    • 2015-02-17
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多