dasuntharanga's avatar

How to upload an image by binding directly to model properties in Livewire?

According to the official livewire docs we can bind data to the eloquent model's properties directly like the following:

use App\Post;

class PostForm extends Component
{

    public Post $post;
    
    protected $rules = [
        'post.title' => 'required|string|min:6',
        'post.content' => 'required|string|max:500',
    ];

    public function save()
    {
        $this->validate();
 
        $this->post->save();
    }

}
<form wire:submit.prevent="save">
    <input type="text" wire:model="post.title">
 
    <textarea wire:model="post.content"></textarea>
 
    <button type="submit">Save</button>
</form>

But how can I upload an image and bind it to the model directly using the same approach?

0 likes
2 replies
LaryAI's avatar
Level 58

To upload an image and bind it to the model directly using Livewire, you can use the wire:model directive on a file input field. Here's an example:

use App\Post;
use Livewire\WithFileUploads;

class PostForm extends Component
{
    use WithFileUploads;

    public Post $post;
    public $image;

    protected $rules = [
        'post.title' => 'required|string|min:6',
        'post.content' => 'required|string|max:500',
        'image' => 'image|max:1024', // validation rules for the image
    ];

    public function save()
    {
        $this->validate();

        $this->post->image = $this->image->store('public/images'); // save the image to storage
        $this->post->save();
    }

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

In the example above, we're using the WithFileUploads trait to enable file uploads in Livewire. We've added a new public property $image to the component, which will hold the uploaded image. We've also added a new validation rule for the image.

In the save method, we're validating the form data, then storing the uploaded image in the public/images directory using the store method. Finally, we're saving the post to the database.

In the view, we can add a file input field with the wire:model directive to bind the uploaded image to the $image property:

<form wire:submit.prevent="save">
    <input type="text" wire:model="post.title">
    <textarea wire:model="post.content"></textarea>
    <input type="file" wire:model="image">
    <button type="submit">Save</button>
</form>

Note that we've added a new file input field with the wire:model directive bound to the $image property. When the form is submitted, the uploaded image will be available in the $image property, which we can then save to the database.

1 like
dasuntharanga's avatar

@LaryAI Thanks for the answer. This should work. but is there any option to keep the same approach?

Please or to participate in this conversation.