Skip to content

All topics  /  Laravel

Laravel Livewire Image upload

Laravel

Teams applying “Laravel Livewire Image upload” in a production project can use more details are available here to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the official Laravel website and test it against the project’s actual database and runtime.

Jun 11, 2020

Hi Dev,

In this blog, I will learn you image upload using livewire package in laravel.I write blog step by step about image upload using liviwire in laravel. I also added validation with image upload liviwire in laravel.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communication.

I added image upload validation like image, mimes, max file upload etc, So you can easily understand and you it simply.

Here I will give full example for livewire image uplaod example laravel So Lets follow the bellow step.

Step 1 : Install Laravel App


In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

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

Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3 : Create Table Migration and Model

In this step we have to create migration for images table and Image Model using laravel php artisan command, so first fire bellow command:

php artisan make:model Image -m

After this command you have to put bellow code in your migration file for create images table.

/database/migrations/2020_06_11_100722_create_images_table.php

<?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');
    }
}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your Image model file for create images table.

app/Image.php

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

Step 4 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire	

Step 5 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create image form component:

php artisan make:livewire image-form	

Now they created fies on both path:

app/Http/Livewire/ImageForm.php
resources/views/livewire/image-form.blade.php

Now both file we will update as bellow for our image form.

app/Http/Livewire/ImageForm.php

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Image;
class ImageForm extends Component
{
    use WithFileUploads;
    public $title;
    public $image;

  
    public function submit()
    {
        $validatedData = $this->validate([
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,svg,jpg,gif|max:1024',
        ]);
        $imageName = $this->image->store("images",'public');
        $validatedData['name'] = $imageName;
        Image::create($validatedData);

  
        session()->flash('message', 'Image successfully Uploaded.');
        return redirect()->to('/image');
    }
    public function render()
    {
        return view('livewire.image-form');
    }
}

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

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

Step 6 : Add Route now, we need to add route for image form in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php

Route::get('/image', function () {
    return view('image');
}); 

Step 7 : Create View File

Here, we will create blade file for call form route. in this file we will use @livewireStyles, @livewireScripts and @livewire('image-form'). so let's add it.

resources/views/image.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>laravel livewire image ipload - nicesnippets.com</title>
    @livewireStyles
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
    <div class="container ">
        <div class="row mt-5">
            <div class="col-md-8 offset-2">
                <div class="card mt-5">
                  <div class="card-header bg-success">
                    <h2 class="text-white">Laravel Livewire Image Ipload - NiceSnippets.com</h2>
                  </div>
                  <div class="card-body">
                    @livewire('image-form')
                  </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
</html>	

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/image

It will help you...