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
How to Force Redirect Http to Https in Laravel
How to Force Redirect Http to...

In this small artical we will see how to force redirect http to https in laravel, Here i will show you two method in&nbs...

Read More

Aug-11-2021

How To File Upload With Progress Bar Angular 15
How To File Upload With Progre...

In this article, we will explore how to implement a file upload feature in Angular 15 with a progress bar. We will guide...

Read More

Jun-23-2023

How To Create Candlestick Chart In Laravel 9 Using Highcharts
How To Create Candlestick Char...

In this article, we will see how to create a candlestick chart in laravel 9 using highcharts. A candlestick is a ty...

Read More

Oct-06-2022

How To Generate QRcode In Laravel
How To Generate QRcode In Lara...

In this example, I will give information about how to generate QR code in laravel. As per the current trend, many w...

Read More

Jun-01-2020