How to Upload Files with Laravel, Inertia js and Vue js Part 1

1 year ago admin Laravel

In today's, tutorial we are going to see how to upload files using Laravel, Inertia js, and Vue js, let's assume that we have an app where the user can upload and update his profile picture.


Create the migration

First, we create the migration the field photo_url will contain the path to the user's profile picture, until now it will take a default image URL from pixabay.

                                                    
                                                                                                                
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('photo_url')->default('https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460__480.png');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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


Create the controller

Next, we create the ProfileController.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    //
    public function profile() {
        return Inertia::render('User/Profile');
    }

    public function updateProfileImage(Request $request) {
        $this->validate($request, [
            'photo_url' => 'mimes:jpg,png,jpeg,webp|max:200000'
        ]);

        if(Storage::disk('public')->exists(auth()->user()->photo_url)) {
            Storage::disk('public')->delete(auth()->user()->photo_url);
        }

        $file = $request->file('photo_url');
        $path = $file->store('profiles', 'public');

        auth()->user()->update([
            'photo_url' => $path
        ]);

        return redirect()->route('profile')->with([
            'message' => 'Image uploaded successfully',
            'class' => 'alert alert-success'
        ]);
    }
}


Get the currently logged in user & display flash messages

Next, to get the currently logged-in user and display flash messages update the file Middlware/HandleInertiaRequests.php.

                                                        
                                                                                                                        
<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Defines the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            //
            'flash' => [
                'message' => fn () => $request->session()->get('message'),
                'class' => fn () => $request->session()->get('class')
            ],
            'user' => fn () => $request->user() ? 
                $request->user()->only(['id', 'name', 'email', 'photo_url', 'image'])
                : null,
        ]);
    }
}

Related Tuorials

How to Prevent the Loop Incrementing Operator from Resetting Back to 1 in the Next Pagination Pages in Laravel

In this lesson, we will see how to prevent the loop incrementing operator from resetting back to 1 i...


How to Logout a User from the Other Devices in Laravel 11

In this lesson, we will see how to logout a user from the other devices in Laravel 11, sometimes you...


How to Logout a User from the Current Device in Laravel 11

In this lesson, we will see how to logout a user from the current device in Laravel 11, sometimes yo...


How to Import Multiple Classes from a Single Namespace in Laravel

In this lesson, we will see how to import multiple classes from a single namespace in Laravel by add...


Laravel 11 Livewire CRUD Application Tutorial Part 2

In the second part of this tutorial, we will display all the tasks on the home page and later we wil...


Laravel 11 Livewire CRUD Application Tutorial Part 1

This tutorial will show us how to create a Laravel 11 Livewire CRUD application. The user can c...


How to Conditionally Include a Blade Template in Laravel

In this lesson, we will see how to conditionally include a blade template in Laravel.Sometimes,...


How to Include a Blade Template Only if it Exists in Laravel

In this lesson, we will see how to include a blade template only if it exists in Laravel.Sometimes,&...


How to Pass a Variable to Include in Laravel

In this lesson, we will see how to pass a variable to include in Laravel. Sometimes, we want to pass...


How to the Get the Previous and Next Posts in Laravel

In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you ge...