Search code examples
phplaravellaravel-livewire

Uploading multiple images with livewire


I'm using livewire, and I am trying to upload multiple images for a post . However, I can't get it to work. When I create a post with images, no images are saved to the database

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

Solution

  • for storing multiple images:

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

    you can use the document for more information: https://laravel-livewire.com/docs/2.x/file-uploads#multiple-files

    P.S: when you're using Post::create you don't need $post->save, and use auth Middleware in your routes.