Laravel 9 Livewire Image Upload Example

Websolutionstuff | Dec-01-2022 | Categories : Laravel

In this article, we will see the laravel 9 livewire image upload example. Here, we will learn how to upload an image using livewire in laravel 8 and laravel 9. Also, you can validate the file size, and file types of image upload in laravel 9. To upload the image, we will add the WithFileUploads trait to your component.

Also, we will upload images and store in the database in laravel 8 and laravel 9. You can also store images on different storage systems like local filesystem disks, and Amazone s3 buckets. Also, we will install just the livewire package.

So, let's see livewire image upload in laravel 9, livewire image upload with preview in laravel 9, and image upload in laravel 9

Step 1: Install Laravel 9

In this step, we will install laravel 9 using the following command.

composer create-project --prefer-dist laravel/laravel livewire_image_upload

 

 

Step 2: Create Migration and Model

Now, we will create a migration and model for image upload using the following command.

php artisan make:migration create_images_table

Migration:

<?php
    
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
    
class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('name');
            $table->timestamps();
        });
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

After that, we will migrate the table into the database and create an images table.

php artisan migrate

Now, we will create Image Mode using the following command.

php artisan make:model Image

app/Models/Image.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Image extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title','name'
    ];
}

 

 

Step 3: Install Livewire

In this step, we will install laravel livewire using the following composer command.

composer require livewire/livewire

 

Step 4: Create Livewire Component

Now, we will create a livewire image upload component using the following command.

php artisan make:livewire image-upload

app/Http/Livewire/image-upload.php

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Image;
  
class ImageUpload extends Component
{
    use WithFileUploads;
    public $file, $title;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function submit()
    {
        $validatedData = $this->validate([
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $validatedData['name'] = $this->image->store('images', 'public');
  
        Image::create($validatedData);
  
        session()->flash('message', 'Image Uploaded Successfully');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.image-upload');
    }
}

resources/views/livewire/image-upload.blade.php

<form wire:submit.prevent="submit" enctype="multipart/form-data">
  
    <div>
        @if(session()->has('message'))
            <div class="alert alert-success">
                {{ session('message') }}
            </div>
        @endif
    </div>
  
    <div class="form-group">
        <label for="exampleInputName">Title:</label>
        <input type="text" class="form-control" id="exampleInputName" placeholder="Enter title" wire:model="title">
        @error('title') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <label for="exampleInputName">File:</label>
        <input type="file" class="form-control" id="exampleInputName" wire:model="image">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-success">Save</button>
</form>

 
 
Step 5: Create Route

In this step, we will add routes to the web.php file.

routes/web.php

Route::get('image-upload', function () {
    return view('default');
});

 

Step 6: Create View File

Now, we will create a blade file and include @livewireStyles, and @livewireScripts.

resources/views/default.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Livewire Image Upload Example - Websolutionstuff</title>
    @livewireStyles
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel 9 Livewire Image Upload Example - Websolutionstuff
      </div>
      <div class="card-body">
        @livewire('image-upload')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

 


You might also like:

Recommended Post
Featured Post
How To Validate Phone Number Using Jquery Input Mask
How To Validate Phone Number U...

In this small tutorial, I will explain to you how to validate phone numbers using jquery input mask, Using jqu...

Read More

Jun-12-2020

How to Remove Elements From JavaScript Array
How to Remove Elements From Ja...

Today we will learn how to remove elements from javascript array, you can use diffrents javascript array...

Read More

Apr-07-2021

How To Get Current User Location In Laravel
How To Get Current User Locati...

In this example, I will show you how to get the current user location in laravel, Many times we are required to find the...

Read More

Jun-10-2020

How to Read CSV File in Python Example
How to Read CSV File in Python...

In this article, I'll show you how to read CSV files in Python. Using Python, we can easily read CSV files line by l...

Read More

Sep-18-2024