Laravel 10 Vue js Axios File Upload Validation

Laravel 10 Vue js Axios File Upload Validation

If you are developing a web application using Laravel and Vue.js, and you need to implement file image upload functionality with validation using Axios, then this tutorial is for you.

The tutorial will guide you through the process of setting up the necessary components and dependencies to enable file image uploads. It will demonstrate how to handle file validation on the server-side using Laravel 10 vue js, as well as how to send the files from the client side using Axios.

File Upload Validation in Laravel 10 Vue js Axios

Steps to implement file image uploads with validation in a Laravel 10 Vue.js web application using Axios:

  • Step 1: Setup Laravel 10 Application
  • Step 2: Configure Database to Laravel App
  • Step 3: Create a Model And Migration
  • Step 4: Install and Configure Vue.js
  • Step 5: Add Routes
  • Step 6: Create Server-side handling Function
  • Step 7: Create Image File Upload Vue Component
  • Step 8: Configure Components with App
  • Step 9: Run Development Server

Step 1: Setup Laravel 10 Application

In this step, Open your terminal or cmd(command prompt).

Then you need to execute the following command into it to install laravel latest application setup in server:

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

Step 2: Configure Database to Laravel App

Once you have installed Laravel web application. Then you need to configure the database with the app.

So, visit the routes directory and open the .env file. And configure database details like following:

 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 a Model And Migration

Next step, you need to execute the following command on the terminal to create the model and migration file:

php artisan make:model Photo -m

This command will create one model name photo.php and also create one migration file for the photos table.

Now open the create_photos_table.php migration file from database>migrations and replace up() function with the following code:

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

Next, migrate the table using the below command:

php artisan migrate

Step 4: Install and Configure Vue.js

Now, you need to install and configure vue js in laravel apps. So, execute the following command on terminal or cmd to install Vue dependencies using NPM:

php artisan preset vue

Install all Vue dependencies:

npm install

Step 5: Add Routes

Next step, go to routes folder and open web.php file and add the following routes into your file:

routes/web.php

Route::get('upload_file', function () {
    return view('upload');
});
use App\Http\Controllers\FileUploadController;

Route::post('store_file', [FileUploadController::class, 'fileStore']);

Step 6: Create Server-side handling Function

Next step, open your command prompt and execute the following command on terminal to create a controller by an artisan:

php artisan make:controller FileUploadController

After that, go to app\Http\Controllers and open FileUploadController.php file. Then update the following code into your FileUploadController.php file:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Models\Photo;
class FileUploadController extends Controller
{
    // function to store file in 'upload' folder
    public function fileStore(Request $request)
    {
        $upload_path = public_path('upload');
        $file_name = $request->file->getClientOriginalName();
        $generated_new_name = time() . '.' . $request->file->getClientOriginalExtension();
        $request->file->move($upload_path, $generated_new_name);
        
        $insert['title'] = $file_name;
        $check = Photo::insertGetId($insert);
        return response()->json(['success' => 'You have successfully uploaded "' . $file_name . '"']);
    }
}

Step 7: Create Image File Upload Vue Component

Next step, go to resources/assets/js/components folder and create a filed called FileUpload.vue.

And update the following code into your FileUpload.vue components file:

<template>
    <div class="container" style="margin-top: 50px;">
        <div class="text-center">
            <h4>File Upload with VueJS and Laravel</h4><br>
            <div style="max-width: 500px; margin: 0 auto;">
                <div v-if="success !== ''" class="alert alert-success" role="alert">
                    {{success}}
                </div>
                <form @submit="submitForm" enctype="multipart/form-data">
                    <div class="input-group">
                        <div class="custom-file">
                            <input type="file" name="filename" class="custom-file-input" id="inputFileUpload"
                                   v-on:change="onFileChange">
                            <label class="custom-file-label" for="inputFileUpload">Choose file</label>
                        </div>
                        <div class="input-group-append">
                            <input type="submit" class="btn btn-primary" value="Upload">
                        </div>
                    </div>
                    <br>
                    <p class="text-danger font-weight-bold">{{filename}}</p>
                </form>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        mounted() {
            console.log('Component successfully mounted.')
        },
        data() {
            return {
                filename: '',
                file: '',
                success: ''
            };
        },
        methods: {
            onFileChange(e) {
                //console.log(e.target.files[0]);
                this.filename = "Selected File: " + e.target.files[0].name;
                this.file = e.target.files[0];
            },
            submitForm(e) {
                e.preventDefault();
                let currentObj = this;
                const config = {
                    headers: {
                        'content-type': 'multipart/form-data',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    }
                }
                // form data
                let formData = new FormData();
                formData.append('file', this.file);
                // send upload request
                axios.post('/store_file', formData, config)
                    .then(function (response) {
                        currentObj.success = response.data.success;
                        currentObj.filename = "";
                    })
                    .catch(function (error) {
                        currentObj.output = error;
                    });
            }
        }
    }
</script>

Now open resources/assets/js/app.js and include the FileUpload.vue component like this:app.js

require('./bootstrap');
window.Vue = require('vue');
Vue.component('file-upload-component', require('./components/FileUpload.vue').default);
const app = new Vue({
    el: '#app',
});

Step 8: Configure Components with App

In this step, you need to create a blade view file to define Vue’s app. Go to resources/views folder and make a file named upload.blade.php. Then update the following code into upload.blade.php as follow:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <title>File Upload with VueJS and Laravel - tutsmake.com</title>
    <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
</head>
<body>
<div id="app">
    <file-upload-component></file-upload-component>
</div>
<script src="{{asset('js/app.js')}}"></script>
</body>
</html>

Step 9: Run Development Server

Now, execute the following command on terminal to start development server:

npm run dev
or 
npm run watch

Conclusion

In this example tutorial, you have learned how to upload files with vue js in laravel using axios request.

Recommended Laravel 10 Posts

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.

Leave a Reply

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