Laravel 10 Livewire File Upload Validation Example

Laravel 10 Livewire File Upload Validation Example

If you’re looking to upload a file with validation using the Livewire package in your Laravel web application, this tutorial is for you. By following this tutorial, you’ll learn how to implement file upload functionality with validation in a Laravel 10 app using the Livewire package.

Laravel 10 Livewire File Upload Validation Example

By following the steps, you can create file upload functionality with validation in a Laravel 10 app using the Livewire package.

  • Step 1: Setup New Laravel 10 Project
  • Step 2: Configure Database with Laravel Project
  • Step 3: Create Model & Migration For File using Artisan
  • Step 4: Install and Configure Livewire Package
  • Step 5: Create Livewire File Upload Component
  • Step 6: Add Routes
  • Step 7: Create Blade View and Import File Upload Component
  • Step 8: Run Development Server

Step 1: Setup New Laravel 10 Project

First of all, Open your terminal OR command prompt(cmd).

Then execute the following command into it to download and install laravel new app in your server:

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

Step 2: Configure Database with Laravel Project

Once you have installed laravel web application in your server. Then you need to configure database with laravel apps.

So open your project root directory and find .env file. Then add database detail in .env file:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=here your database name here 
DB_USERNAME=here database username here 
DB_PASSWORD=here database password here

Step 3: Create Model & Migration For File using Artisan

In this step, generate model and migration file using the following command:

php artisan make:model Document -m

This command will create one model name Document.php and also create one migration that name create_documents_table.php.

So, Navigate to database/migrations folder and open create_documents_table.php file. Then update the following code into create_documents_table.php file:

<?php

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

class CreateDocumentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('file_name');
            $table->timestamps();
        });
    }

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

Once you have code in migration file. Now you need to open your command prompt or terminal and execute the following command to create the table into your database:

php artisan migrate

Now, Open App/Document.php file and add the fillable properties:

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Document extends Model
{
     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'file_name'
    ];
}

Step 4: Install and Configure Livewire Package

In this step, you need to install livewire package to your laravel project using the following command:

composer require livewire/livewire

Step 5: Create Livewire File Upload Component

In this step, create the livewire components for creating a livewire image upload component using the following command. So Open your cmd and run the following command:

php artisan make:livewire lara-file-upload

This command will create the following components on the following path:

app/Http/Livewire/LaraFileUpload.php
resources/views/livewire/lara-file-upload.blade.php

Now, Navigate to app/Http/Livewire folder and open LaraFileUpload.php file. Then add the following code into your LaraFileUpload.php file:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Document;

class LaraFileUpload extends Component
{
    use WithFileUploads;

    public $title;
	public $file_name;

    public function submit()
    {
        $data = $this->validate([
            'title' => 'required',
            'file_name' => 'required',
        ]);

        $filename = $this->file_name->store('documents','public');

        $data['file_name'] = $filename;

        Document::create($data);

        session()->flash('message', 'File has been successfully Uploaded.');

        return redirect()->to('/lara-livewire-file-upload');
    }

    public function render()
    {
        return view('livewire.lara-file-upload');
    }
}

After that, Navigate to resources/views/livewire folder and open lara-file-upload.blade.php file. Then add the following code into your lara-file-upload.blade.php file:

@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="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="name">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>

    <button type="submit">Save</button>
</form>

Step 6: Add Routes

In this step, Navigate to routes folder and open web.php. Then add the following routes into your web.php file:

Route::get('lara-livewire-file-upload', function () {
    return view('welcome');
});

Step 7: Create Blade View and Import File Upload Component

In this step, navigate to resources/views/livewire folder and create one blade view files that name welcome.blade.php file. Then add the following code into your welcome.blade.php file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 10 Livewire File Upload Example From Scratch - Tutsmake.com</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
<body>
    <div class="container mt-5">
        <div class="row mt-5 justify-content-center">
            <div class="mt-5 col-md-8">
                <div class="card">
                  <div class="card-header bg-success">
                    <h2 class="text-white">Laravel Livewire File Upload Example From Scratch - tutsmake.com</h2>
                  </div>

                    <div class="card-body">
                       @livewire('lara-file-upload')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>
Note that, if you want to add HTML(blade views), CSS, and script code into your livewire files. So, you can use @livewireStyles, @livewireScripts, and @livewire(‘ blade views’).

Step 8: Run Development Server

Finally, you need to run the following PHP artisan serve command to start your laravel livewire upload file app:

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now, you are ready to run laravel livewire file upload app. So open your browser and hit the following URL into your browser:

http://localhost:8000/lara-livewire-file-upload

Recommended Laravel tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Laravel 10 Livewire File Upload Validation Example

  1. Hi, how about filepath for that document?

Leave a Reply

Your email address will not be published. Required fields are marked *