How to Delete Files from OneDrive in Laravel 11

Websolutionstuff | Dec-24-2024 | Categories : Laravel

Managing files in cloud storage is essential for modern web applications. In this article, I’ll show you how to delete files from OneDrive in a Laravel 11 application using the Microsoft Graph API.

You’ll learn how to authenticate users, list uploaded files, and delete files with simple and clear code examples.

Step-by-Step Guide to Delete Files from OneDrive in Laravel 11

Step-by-Step Guide to Delete Files from OneDrive in Laravel 11

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 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 App\Http\Controllers\OneDriveController;
use Illuminate\Support\Facades\Route;

Route::get('/login', [OneDriveController::class, 'redirectToProvider']);
Route::get('/callback', [OneDriveController::class, 'handleProviderCallback']);
Route::get('/files', [OneDriveController::class, 'listFiles'])->name('files.list');
Route::delete('/files/{id}', [OneDriveController::class, 'deleteFile'])->name('files.delete');

 

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()->route('files.list')->with('success', 'You are logged in!');
    }

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

        $files = $graph->createRequest("GET", "/me/drive/root/children")
            ->setReturnType(Model\DriveItem::class)
            ->execute();

        return view('files', ['files' => $files]);
    }

    public function deleteFile($id)
    {
        $graph = new Graph();
        $graph->setAccessToken(session('microsoft_token'));

        $graph->createRequest("DELETE", "/me/drive/items/{$id}")
            ->execute();

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

 

Step 8: Create Upload Form View

Create resources/views/files.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Manage Files in OneDrive</title>
</head>
<body>
    <h1>Files in OneDrive</h1>

    @if(session('success'))
        <p style="color: green;">{{ session('success') }}</p>
    @endif

    <table border="1">
        <thead>
            <tr>
                <th>File Name</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach($files as $file)
                <tr>
                    <td>{{ $file->getName() }}</td>
                    <td>
                        <form action="{{ route('files.delete', $file->getId()) }}" method="POST" onsubmit="return confirm('Are you sure?');">
                            @csrf
                            @method('DELETE')
                            <button type="submit">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
</body>
</html>

 


You might also like:

Recommended Post
Featured Post
Send Mail Example In Laravel 8
Send Mail Example In Laravel 8

In this article, we will see send mail in laravel 8. here we will see how to send mail in laravel 8. Emai...

Read More

Oct-16-2020

Mail: Laravel 11 Send Email using Queue
Mail: Laravel 11 Send Email us...

In this guide, we'll see how to send email using a queue in laravel 11. Here we'll see the concept of queue...

Read More

Apr-12-2024

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 10 Livewire Multi Step Form Wizard
Laravel 10 Livewire Multi Step...

Hello developers! Today, I'm excited to walk you through the process of creating a multi-step form wizard using...

Read More

Dec-18-2023