How to Upload Files to OneDrive in Laravel 11

Websolutionstuff | Dec-19-2024 | Categories : Laravel

Uploading files to cloud storage services like OneDrive can simplify file management in web applications. In this article, I’ll guide you through integrating OneDrive into your Laravel 11 project, enabling file uploads using Microsoft Graph API.

This step-by-step tutorial will cover setting up a OneDrive app, configuring your Laravel application, and implementing file uploads with code examples.

Step-by-Step Guide to Upload Files to OneDrive in Laravel 11

Step-by-Step Guide to Upload Files to OneDrive in Laravel 10

 

Step 1: Create a Microsoft App
  • Visit the Azure Portal.
  • Navigate to Azure Active Directory > App Registrations.
  • Click New Registration.
  • Enter a Name, choose Accounts in any organization, and add a Redirect URI like http://localhost:8000/callback.
  • Click Register

 

Step 2: Configure API Permissions
  • In your app, go to API Permissions.
  • Click Add Permission > Microsoft Graph > Delegated Permissions.
  • Select Files.ReadWrite.All, then click Add Permissions.
  • Grant admin consent if needed

 

Step 3: Get App Credentials
  • Go to Certificates & Secrets.
  • Create a new Client Secret and copy the Value.
  • Save the Application (Client) ID and Directory (Tenant) ID from the app overview

 

Step 4: Install Required Packages

Run the following command to install the required packages:

composer require league/oauth2-client microsoft/microsoft-graph

 

Step 5: Set Environment Variables

Add these to your env file:

MICROSOFT_CLIENT_ID=your-client-id
MICROSOFT_CLIENT_SECRET=your-client-secret
MICROSOFT_REDIRECT_URI=http://localhost:8000/callback
MICROSOFT_TENANT_ID=your-tenant-id

 

Step 6: Create Authentication Logic

Add the following routes to web.php:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OneDriveController;

Route::get('/login', [OneDriveController::class, 'redirectToProvider']);
Route::get('/callback', [OneDriveController::class, 'handleProviderCallback']);
Route::post('/upload', [OneDriveController::class, 'uploadFile'])->name('upload');
Route::get('/upload-form', function () {
    return view('upload');
});

 

Step 7: Create the OneDrive Controller

Create a OneDrive Controller and add the following code to that file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;

class OneDriveController extends Controller
{
    public function redirectToProvider()
    {
        $authUrl = 'https://login.microsoftonline.com/' . env('MICROSOFT_TENANT_ID') . '/oauth2/v2.0/authorize?' . http_build_query([
            'client_id' => env('MICROSOFT_CLIENT_ID'),
            'response_type' => 'code',
            'redirect_uri' => env('MICROSOFT_REDIRECT_URI'),
            'scope' => 'Files.ReadWrite.All offline_access',
            'response_mode' => 'query'
        ]);

        return redirect($authUrl);
    }

    public function handleProviderCallback(Request $request)
    {
        $tokenRequestData = [
            'client_id' => env('MICROSOFT_CLIENT_ID'),
            'client_secret' => env('MICROSOFT_CLIENT_SECRET'),
            'code' => $request->query('code'),
            'redirect_uri' => env('MICROSOFT_REDIRECT_URI'),
            'grant_type' => 'authorization_code'
        ];

        $response = Http::asForm()->post(
            'https://login.microsoftonline.com/' . env('MICROSOFT_TENANT_ID') . '/oauth2/v2.0/token',
            $tokenRequestData
        );

        session(['microsoft_token' => $response['access_token']]);

        return redirect('/upload-form')->with('success', 'You are logged in! You can upload files now.');
    }

    public function uploadFile(Request $request)
    {
        $graph = new Graph();
        $graph->setAccessToken(session('microsoft_token'));

        $fileContent = file_get_contents($request->file('file')->getRealPath());

        $graph->createRequest("PUT", "/me/drive/root:/uploads/" . $request->file('file')->getClientOriginalName() . ":/content")
            ->attachBody($fileContent)
            ->execute();

        return back()->with('success', 'File uploaded successfully.');
    }
}

 

Step 8: Create Upload Form View

Create resources/views/upload.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Upload to OneDrive</title>
</head>
<body>
    <h1>Upload File to OneDrive</h1>
    @if(session('success'))
        <p>{{ session('success') }}</p>
    @endif
    <form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="file" required>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

 


You might also like:

Recommended Post
Featured Post
Laravel 8 Eloquent whereHas Condition
Laravel 8 Eloquent whereHas Co...

In this example we will see laravel 8 eloquent whereHas() condition. you will learn about wherehas() condition in l...

Read More

Oct-06-2021

How To Create Unique Slug In Laravel 9
How To Create Unique Slug In L...

In this article, we will see how to create a unique slug in laravel 9. A slug is the part of a URL that i...

Read More

Sep-27-2022

Laravel 8 Form Validation Example
Laravel 8 Form Validation Exam...

In this article, we will see the laravel 8 form validation example. form validation in laravel is a very common fun...

Read More

Oct-10-2020

Laravel tips DB Models and Eloquent - Part 3
Laravel tips DB Models and Elo...

Welcome back to the third installment of our series on Laravel tips for database models and Eloquent. If you've been...

Read More

Oct-16-2023