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 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...


How Do you Format a Number as K/M/B in Laravel

In this lesson, we will see how to format a number as K/M/B in Laravel, sometimes we want to display...


How to Override Laravel Fortify Default Registration Redirect

In this lesson, we will see how to override Laravel Fortify default registration redirect, sometimes...


How to Override Laravel Fortify Default Login Redirect

In this lesson, we will see how to override Laravel Fortify default login redirect, sometimes when w...


How to Use the Same Validation Form Request for both Create and Update in Laravel

In this lesson, we will see how to use the same validation form request for both create and update i...


How to Get Raw SQL Output from the Eloquent Model in Laravel 11

In this lesson, we will see how to get raw SQL output from the eloquent model in Laravel 11, sometim...


How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...