Laravel 7.x Vue Js Image Upload Using Image Intervention

Hello Artisan

Now i am working on a project where i made a custom login and registration system in laravel using vue js. There is user image upload option. So now i am going to show you laravel vue image upload example from scratch.

In this image upload with laravel vue js tutorial i will use image intervention. You know  that Intervention Image is an open source PHP image handling and manipulation library. It provides an easier and expressive way to create, edit, and compose images 

So in this laravel vue axios file upload tutorial i will also use v-form for our form validation before submit the form data. I will show you also instant image upload with live preview. We will convert our image file into base64 and then we will convert it into image file using image intervention in our controller.

If you are a web developer, you will know thet in today's web app Image or File upload is a common task. The client requires to image or file upload in his web application like a profile section, product image or many other.

So let's start vue js image upload laravel 7 example from scratch. You can see the preview from below image. 

Preview | Instant image showing and form validation

 

Step 1 : Install Laravel 7 

Now download laravel 7 fresh project to do it from scratch. You can also integrate it in your existing project. Run below command to download laravel 7.

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

 

Step 2: Create Route

In this step we need to create our route for image upload with vue js in laravel. 

routes/web.php

use Illuminate\Support\Facades\Route;

Route::post('/register','[email protected]_signup');

 

Step 3 : Setup User Model

In this step we have to setup our User model. We add mutator here to mutate our password. 

app/User.php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = \Hash::make($value);
    }
}

 

Step 4: Create Controller

Now we need to create auth controller to complete image upload using vue js in laravel 7 application. Now create auth controller and paste this below code.

app/Http/Controllers/AuthController.php

namespace App\Http\Controllers;

use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\View;

class AuthController extends Controller
{   

    public function process_signup(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'avatar' => 'required'
        ]);

        if($request->avatar){

            $name = time().'.' . explode('/', explode(':', substr($request->avatar, 0, strpos($request->avatar, ';')))[1])[1];
            \Image::make($request->avatar)->save(public_path('img/profile/').$name);
            $request->merge(['avatar' => $name]);
           
        }
        
        $user = new User;
        $user->username = $request->username;
        $user->avatar = $name;
        $user->save();
        
        return response()->json(
            [
                'success' => true,
                'message' => 'User registered successfully'
            ]
        );

    }
}

 

Step 5 : Create Migration

Now we have to migrate our users table. Open open users migration file and paste below code.

database/migration/users

 Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username')->unique();
            $table->string('avatar');
            $table->rememberToken();
            $table->timestamps();
});

 

Read also : Laravel 7 Ajax Image Upload with Preview

now run php artisan migrate to migrate this table. Now time to setup vue dependencies. 

Step 6:  Vue Configuration

If you would like to install vue in your laravel 7 project then run following laravel ui composer package command to install.

composer require laravel/ui

and then install vue

php artisan ui vue

now we have to install npm

npm install

 

Now we have to install v-form in our project to validate form data before submit. So install it

npm i axios vform

 

Step 7 : Configure app.js

Now open app.js file and paste this below code

require('./bootstrap');

window.Vue = require('vue');

//Import v-from
import { Form, HasError, AlertError } from 'vform'
window.Form = Form;
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)

Vue.component('register-component', require('./components/RegisterComponent.vue').default);

const app = new Vue({
    el: '#app',
});

 

Step 8 : Create Vue Component

Now we have to create register component to write our view function. So create it and paste this following code to it.

resources/js/components/RegisterComponent.vue

 

Step 8:  Create Blade File

At last step, we will update our register.blade.php file. in this file we will use app.js file and use it, so let's update.

 

Step 9 :  Install Image Intervention

To install the most recent version, run the following command.

composer require intervention/image

 

After you have installed Intervention Image, open your Laravel config file config/app.php and add the following lines. In the $providers array add the service providers for this package.

config/app.php

Intervention\Image\ImageServiceProvider::class

Add the facade of this package to the $aliases array.

'Image' => Intervention\Image\Facades\Image::class

Now the Image Class will be auto-loaded by Laravel.

Publish configuration in Laravel

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

 

Now we are ready to run our example app that is vue js laravel 7 image upload tutorial. Just one more thing.

Step 10 :  Create img/profile folder

Now we have to create  img/profile directory in your public folder to store our image. so now create it. After doing it everything is done. So now compile our all javascript file.

npm run watch

 

Read also : Laravel 6 REST API with JWT Authentication with CRUD

Hope it will work for you. If you face any error, feel free to comment.