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,
        ]);
    }
}

Popular Tutorials

Related Tutorials

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


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...