Livewire File Upload Laravel

  • 12-07-2022
  • 1063
  • Laravel 9
  • Haresh Chauhan

Image uploading using laravel livewire; In this post, we will learn how to upload an image and any type of file using livewire. This is a very easy to develop and quick image uploading tool in this modern technology.

Apart from that livewire also provides a lot of methods to upload images with different methods and tools.

Through this post, I will learn how to upload an image using a livewire image through the laravel step-by-step process. So just follow the step with me and integrate into your project.

I am starting this post with a fresh new laravel project, if you already have a laravel project you can skip this first step. Apart from that if ar integrating into your existing project you can skip steps 1,2 or 3 step. you can start direct from step 4.

OUTPUT PREVIEW :
image

So let's start integrating livewire image upload.

Step 1: Create Laravel Project

We will create a laravel project using the given below command. The project name will be livewire-image. If you want to change the project name you can change in command the last argument.

composer create-project --prefer-dist laravel/laravel livewire-image

Step 2: Database Config

We will configure the database in the .env file. First, we will go to MYSQL database and there we will create a database "image_livewire", Then we will set that database name in our environment file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=image_livewire
DB_USERNAME=root
DB_PASSWORD=

Step 3: Make Model & Migration

Create a model with a migration file, Here we will create an ImageUpload model and migration file for the image name and name stored in the database table.

Use the below-given command in your terminal and generate.

php artisan make:model ImageUpload -m

We will add two columns in this "image_uploads" table one for the store name and the second for the store image path where we stored it.

database/migrations/2022_07_12_154743_create_image_uploads_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImageUploadsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('image_uploads', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');   
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('image_uploads');
    }
}

We will add these two files to the model in the fillable property.

app/Models/ImageUpload.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ImageUpload extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'image',
    ];
}

Then we will migrate our migration using the below command in our terminal, This will migrate and create the image_uploads table in our database.

php artisan migrate

Step 4: Install Livewire Composer

In this step, we will install livewire composer in our project, Paste and install.

composer require livewire/livewire

Step 5: Create Livewire Component

We will create a livewire controller and component using the below-given command.

php artisan make:livewire image-upload

There are Two files will be generated using the above command in the given path.

app/Http/Livewire/ImageUpload.php
resources/views/livewire/image-upload.blade.php

We will add the image upload method and render to view the file. These two methods are in this livewire component.

app/Http/Livewire/ImageUpload.php
<?php
namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\ImageUpload as ImageUploads;

class ImageUpload extends Component
{
    use WithFileUploads;

    public $name, $image;

    public function render()
    {
        return view('livewire.image-upload')->extends('livewire.layout.app');
    }

    public function submit()
    {
        $data = $this->validate([
            'name' => 'required',
            'image' => 'required|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
        ]);
    
        $data['image'] = $this->image->store('image', 'public');
    
        ImageUploads::create($data);
    
        session()->flash('success', 'File uploaded.');
    }
}        

Goto given path and just paste the below-given code. This is for image upload HTML form.

resources/views/livewire/image-upload.blade.php
<div>
    <form wire:submit.prevent="submit" enctype="multipart/form-data">
        
        <div>
            @if(session()->has('success'))
                <div class="alert alert-success">
                    {{ session('success') }}
                </div>
            @endif
        </div>
        
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Enter title" wire:model="name">
            @error('name') <span class="text-danger">{{ $message }}</span> @enderror
        </div>
        <div class="form-group">
            <input type="file" class="form-control" wire:model="image">
            @error('image') <span class="text-danger">{{ $message }}</span> @enderror
        </div>
        
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
</div>

Finalized, We will create an app blade file in the layout folder inside the laravel views. after creating the file just copy the whole given code and paste it into your app blade file.

resources/views/livewire/layout/app.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 9 Livewire Dropdown Example - Webappfix.com</title>
    @livewireStyles
    <link href="//cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
    @livewireScripts
</html>

Laravel Livewire CRUD Using Bootstrap Modal Full Example Guideline And Demo Source Code

Step 6: Define Route

In this step I have define a route name "image-upload" and this will be our URL for image upload.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Livewire\ImageUpload;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('image-upload',ImageUpload::class);

After defining route we will start our laravel application development server using this command.

php artisan serve

Then Finally go to this URL and upload your file and press the upload button. This will upload your file to your public folder inside the image folder.

http://127.0.0.1:8000/image-upload

Once you press on upload button you will see an image uploaded image with success alert.

Conclusion

We can say Laravel Livewire is very quick and fast too. Using livewire we can upload files and images without refreshing to page and any extra code and complexity. So this is very powerful and modern too in laravel you can integrate it into your application very easily.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :