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
http://localhost:8000/callback
.
Run the following command to install the required packages:
composer require league/oauth2-client microsoft/microsoft-graph
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
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');
});
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.');
}
}
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:
In this example we will see laravel 8 eloquent whereHas() condition. you will learn about wherehas() condition in l...
Oct-06-2021
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...
Sep-27-2022
In this article, we will see the laravel 8 form validation example. form validation in laravel is a very common fun...
Oct-10-2020
Welcome back to the third installment of our series on Laravel tips for database models and Eloquent. If you've been...
Oct-16-2023