How to Create a Livewire Image Upload in Laravel 10?

Websolutionstuff | Aug-02-2023 | Categories : Laravel

Livewire has revolutionized the way developers build interactive web applications with its real-time capabilities. And with the release of Laravel 10, it's even more powerful.

One of its exciting features is Livewire, which allows us to build interactive UI components using PHP. And now you too can harness its power to create a seamless image upload system that will captivate your users.

In this blog, we'll focus on creating a Livewire Image Upload feature, making your web application more dynamic and user-friendly. We'll walk you through the entire process, from setting up the project to adding the Livewire component to your page.

So, are you ready to level up your Laravel skills?

Building a Livewire Image Upload

Let's get to the exciting part - building the Livewire Image Upload in Laravel 10. We'll take you through the steps with code examples to make it easier for you to follow along.
 

Step 1: Setting Up a New Laravel Application

To begin, open your terminal or command prompt.

Next, enter the following command to install the latest Laravel application on your server:

composer global require laravel/installer

 

Step 2: Setting up the Database

After successfully installing the Laravel app, the next crucial step is to set up a database for your Laravel application.

To begin, navigate to the root directory of your project and locate the .env file. Here, you will configure the database details as shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

 

Step 3: Creating Image Upload Model & Migration

Open the command prompt and execute the following command:

php artisan make:model Image -m

Now, put this code in your migration file to create an image table.

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

Once the above steps are completed, return to the terminal and run migration through the following attributes:

php artisan migrate

After that, you need to put the following code in your Image model file to create an images table.

<?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 4: Installing Livewire Package

To install the Livewire package in your Laravel 10 application, follow these steps:

Open the command prompt or terminal and execute the command below:

composer require livewire/livewire

 

Step 5: Building Components

To create Livewire components in a Laravel 10 app, follow these steps:

Execute the following command in the command prompt:

php artisan make:livewire ImageUpload

This command will create two files, as mentioned below:

  1. imageUpload.php, located in the app/Http/Livewire directory.
  2. image-upload.blade.php, located in the resources/views/livewire/ directory.

Now, open the file ImageUpload.php in the app/Http/Livewire directory and add the following code to it:

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

Next, open the file image-upload.blade.php in the resources/views/livewire/ directory and add the following code to it:

<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 6: Creating Routes

Navigate to the web.php file located in the 'routes' directory. Afterward, insert the provided routes below into the 'web.php' file.:

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/
Route::get('image-upload', function () {
    return view('default');
});

 

Step 7: Creating Blade View

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

resources/views/default.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Create a Livewire Image Upload in Laravel 10? - 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">
        How to Create a Livewire Image Upload in Laravel 10? - Websolutionstuff
      </div>
      <div class="card-body">
        @livewire('image-upload')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

 

Step 8: Starting Development Server

To initiate the development server for your Laravel 10 Livewire image upload application, enter the following command:

php artisan serve

 

Conclusion

Now, you've successfully created a Livewire Image Upload feature in Laravel 10. Now your web app can handle image uploads with ease, thanks to Laravel's powerful API and Livewire's interactive components. 

Keep exploring and experimenting with Laravel to take your web development skills to new heights!

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Livewire File Upload Example
Laravel 9 Livewire File Upload...

In this article, we will see the laravel 9 livewire file upload example. Here, we will learn how to upload files us...

Read More

Dec-02-2022

How to Get Selected Checkbox Value in Array Using jQuery
How to Get Selected Checkbox V...

In this post we will see how to get selected checkbox value in array using jquery. Here i will give you some example to&...

Read More

May-24-2021

How To Store JSON Data In Database Laravel 9
How To Store JSON Data In Data...

In this article, we will see how to store JSON data in the database laravel 9. Laravel 9 stores JSON data in M...

Read More

Sep-28-2022

How To Add Bootstrap Modal In Laravel
How To Add Bootstrap Modal In...

Today I will show you how to add a bootstrap popup modal on button click. many times we need to set confirmation on the...

Read More

May-27-2020