PHP code example of prasadchinwal / microsoft-graph

1. Go to this page and download the library: Download prasadchinwal/microsoft-graph library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

prasadchinwal / microsoft-graph example snippets


return [
    'tenant_id' => env('MICROSOFT_GRAPH_TENANT_ID', null),
    'client_id' => env('MICROSOFT_GRAPH_CLIENT_ID', null),
    'client_secret' => env('MICROSOFT_GRAPH_CLIENT_SECRET', null),
    'timezone' => env('APP_TIMEZONE', 'UTC'),
];

use PrasadChinwal\MicrosoftGraph\Facades\MicrosoftGraph;

// Via Facade
$graph = app('graph');

// Or direct instantiation
$graph = new \PrasadChinwal\MicrosoftGraph\MicrosoftGraph();

use PrasadChinwal\MicrosoftGraph\Facades\MicrosoftGraph;

$users = MicrosoftGraph::users()->get();

foreach ($users as $user) {
    echo $user->displayName . ' - ' . $user->mail;
}

$user = MicrosoftGraph::users()->find('[email protected]');

echo $user->displayName;        // John Doe
echo $user->jobTitle;           // Software Engineer
echo $user->department;         // Engineering
echo $user->mobilePhone;        // +1 234 567 8900

use PrasadChinwal\MicrosoftGraph\Builder\User\User;

$userUpdate = new User();
$userUpdate->displayName = 'Jane Smith';
$userUpdate->jobTitle = 'Senior Software Engineer';
$userUpdate->department = 'Engineering';
$userUpdate->mobilePhone = '+1 234 567 8901';

MicrosoftGraph::users()->update('[email protected]', $userUpdate);

$licenses = MicrosoftGraph::users()
    ->withEmail('[email protected]')
    ->getLicenses();

foreach ($licenses as $license) {
    echo $license->skuPartNumber;
    foreach ($license->servicePlans as $plan) {
        echo $plan->servicePlanName;
    }
}

use PrasadChinwal\MicrosoftGraph\Builder\License\AssignLicenseBuilder;
use PrasadChinwal\MicrosoftGraph\Builder\License\NewLicense;
use PrasadChinwal\MicrosoftGraph\Builder\License\NewLicenseCollection;

$license = new NewLicense();
$license->skuId = 'sku-guid-here';

$licenseCollection = new NewLicenseCollection([$license]);

$builder = new AssignLicenseBuilder(
    addLicenses: $licenseCollection,
    removeLicenses: []
);

$updatedUser = MicrosoftGraph::users()
    ->withEmail('[email protected]')
    ->assignLicense($builder);

$response = MicrosoftGraph::users()
    ->withEmail('[email protected]')
    ->getPhoto();

// Save to file
file_put_contents('profile.jpg', $response->body());

// Or return as response
return response($response->body())
    ->header('Content-Type', 'image/jpeg');

$imageData = file_get_contents('/path/to/photo.jpg');

MicrosoftGraph::users()
    ->withEmail('[email protected]')
    ->updatePhoto($imageData);

MicrosoftGraph::users()
    ->withEmail('[email protected]')
    ->deletePhoto();

$calendars = MicrosoftGraph::calendar()
    ->for('[email protected]')
    ->get();

foreach ($calendars as $calendar) {
    echo $calendar->name;
}

use Carbon\Carbon;

$users = ['[email protected]', '[email protected]'];

$schedule = MicrosoftGraph::calendar()
    ->for('[email protected]')
    ->schedule(
        users: $users,
        from: Carbon::now(),
        to: Carbon::now()->addDays(7),
        timezone: 'America/Chicago',
        interval: 60
    );

use Carbon\Carbon;

$events = MicrosoftGraph::calendar()
    ->for('[email protected]')
    ->view(
        start: Carbon::now()->toIso8601String(),
        end: Carbon::now()->addMonth()->toIso8601String()
    );

$events = MicrosoftGraph::event()
    ->for('[email protected]')
    ->get();

foreach ($events as $event) {
    echo $event->subject;
    echo $event->start->dateTime;
    echo $event->end->dateTime;
}

// Get events within a date range
$events = MicrosoftGraph::event()
    ->for('[email protected]')
    ->where('start/dateTime', 'ge', '2024-01-01')
    ->where('end/dateTime', 'le', '2024-12-31')
    ->get();

// Use OR conditions
$events = MicrosoftGraph::event()
    ->for('[email protected]')
    ->where('subject', 'eq', 'Team Meeting')
    ->orWhere('subject', 'eq', 'All Hands')
    ->get();



namespace App\Mail;

use PrasadChinwal\MicrosoftGraph\Calendar\Event\CalendarEvent;
use PrasadChinwal\MicrosoftGraph\Calendar\Event\Eventable\Envelope;
use PrasadChinwal\MicrosoftGraph\Calendar\Event\Eventable\Attendee;
use PrasadChinwal\MicrosoftGraph\Calendar\Event\Eventable\Enums\CalendarEventImportance;
use Illuminate\Mail\Mailables\Content;
use Carbon\Carbon;

class TeamMeetingEvent extends CalendarEvent
{
    public function envelope(): Envelope
    {
        return new Envelope(
            from: '[email protected]',
            subject: 'Weekly Team Sync',
            attendees: [
                new Attendee('[email protected]', 'John Doe', 

use App\Mail\TeamMeetingEvent;

$response = MicrosoftGraph::event()->create(new TeamMeetingEvent());

$response = MicrosoftGraph::event()->update(
    eventId: 'AAMkAGI2...',
    mailable: new TeamMeetingEvent()
);

MicrosoftGraph::event()
    ->for('[email protected]')
    ->accept(
        eventId: 'AAMkAGI2...',
        message: 'Looking forward to it!'
    );

MicrosoftGraph::event()
    ->for('[email protected]')
    ->decline(
        eventId: 'AAMkAGI2...',
        message: 'Unable to attend due to conflict.'
    );

MicrosoftGraph::event()
    ->for('[email protected]')
    ->cancel(
        eventId: 'AAMkAGI2...',
        message: 'Meeting cancelled due to unforeseen circumstances.'
    );

$messages = MicrosoftGraph::mail()
    ->for('[email protected]')
    ->top(50)
    ->get();

// Get unread messages
$messages = MicrosoftGraph::mail()
    ->for('[email protected]')
    ->where('isRead', '!=', 'true')
    ->top(25)
    ->get();

// Get messages from a specific sender
$messages = MicrosoftGraph::mail()
    ->for('[email protected]')
    ->where('from/emailAddress/address', '=', '[email protected]')
    ->get();

// Filter by received date
$messages = MicrosoftGraph::mail()
    ->for('[email protected]')
    ->where('receivedDateTime', '>=', '2024-01-01T00:00:00Z')
    ->top(100)
    ->get();

// Send to a single recipient
MicrosoftGraph::outlook()
    ->for('[email protected]')
    ->sendEmail(
        subject: 'Project Update',
        message: 'The project is progressing well...',
        to: '[email protected]'
    );

// Send to multiple recipients
MicrosoftGraph::outlook()
    ->for('[email protected]')
    ->sendEmail(
        subject: 'Team Announcement',
        message: 'Please review the attached document...',
        to: [
            '[email protected]',
            '[email protected]',
            '[email protected]'
        ]
    );

use PrasadChinwal\MicrosoftGraph\Facades\MicrosoftGraph;
$data = MicrosoftGraph::teamConfiguration()
        ->where(field: 'id', operator: '=', value: '109c9587-bdf8-4f84-ba53-01c7ab2efa22')
        ->get();
    dd($data->first()->telephoneNumbers->pluck('telephoneNumber'));

use PrasadChinwal\MicrosoftGraph\Facades\MicrosoftGraph;
$data = MicrosoftGraph::teamConfiguration()
        ->where(field: 'id', operator: '=', value: '109c9587-bdf8-4f84-ba53-01c7ab2efa22')
        ->get();
    dd($data->first()->hasEnterpriseVoiceEnabled());

use PrasadChinwal\MicrosoftGraph\Facades\MicrosoftGraph;
$data = MicrosoftGraph::numberAssignement()
        // ->where(field: 'assignmentStatus', operator: '=', value: 'unassigned')
        // ->where('telephoneNumber', '=', '+222222222')
        ->get();
    dd($data);

// List message attachments
$attachments = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->list();

foreach ($attachments as $attachment) {
    echo $attachment->name;
    echo $attachment->contentType;
    echo $attachment->size;
}

// List event attachments
$attachments = MicrosoftGraph::attachments()
    ->forEvent('[email protected]', 'eventId')
    ->list();

$attachment = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->get('attachmentId');

echo $attachment->id;
echo $attachment->name;
echo $attachment->contentType;
echo $attachment->size;
echo $attachment->lastModifiedDateTime;

$response = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->getRaw('attachmentId');

// Save to file
file_put_contents('downloaded_file.pdf', $response->body());

// Or return as HTTP response
return response($response->body())
    ->header('Content-Type', $response->header('Content-Type'));

use PrasadChinwal\MicrosoftGraph\Builder\Attachment\FileAttachmentBuilder;

// Create attachment from file
$builder = FileAttachmentBuilder::fromFile('/path/to/document.pdf');

$attachment = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->addFile($builder);

echo $attachment->id;  // Use this ID for future operations

use PrasadChinwal\MicrosoftGraph\Builder\Attachment\FileAttachmentBuilder;

$imageData = file_get_contents('/path/to/image.jpg');

$builder = FileAttachmentBuilder::fromData(
    data: $imageData,
    name: 'profile-photo.jpg',
    contentType: 'image/jpeg'
);

$attachment = MicrosoftGraph::attachments()
    ->forEvent('[email protected]', 'eventId')
    ->addFile($builder);

use PrasadChinwal\MicrosoftGraph\Builder\Attachment\FileAttachmentBuilder;

$builder = FileAttachmentBuilder::fromFile('/path/to/logo.png')
    ->asInline('logo-cid');

$attachment = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'draftMessageId')
    ->addFile($builder);

// Reference in HTML body as: <img src="cid:logo-cid">

use PrasadChinwal\MicrosoftGraph\Builder\Attachment\ReferenceAttachmentBuilder;

$builder = ReferenceAttachmentBuilder::fromUrl(
    url: 'https://contoso.sharepoint.com/documents/report.xlsx',
    name: 'Q4 Financial Report'
)
->setProvider('oneDriveBusiness')
->setPermission('edit')
->setThumbnail('https://contoso.sharepoint.com/thumbnails/report_thumb.png');

$attachment = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->addReference($builder);

$attachmentData = [
    '@odata.type' => '#microsoft.graph.fileAttachment',
    'name' => 'custom-document.txt',
    'contentBytes' => base64_encode('Hello, World!'),
    'contentType' => 'text/plain',
];

$attachment = MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->create($attachmentData);

MicrosoftGraph::attachments()
    ->forMessage('[email protected]', 'messageId')
    ->delete('attachmentId');

// Or for events
MicrosoftGraph::attachments()
    ->forEvent('[email protected]', 'eventId')
    ->delete('attachmentId');

use PrasadChinwal\MicrosoftGraph\Builder\Attachment\FileAttachmentBuilder;

// 1. Create a draft message
$message = MicrosoftGraph::mail()->createDraft([
    'subject' => 'Project Report',
    'body' => [
        'contentType' => 'HTML',
        'content' => '<p>Please find attached the project report.</p>'
    ],
    'toRecipients' => [
        ['emailAddress' => ['address' => '[email protected]']]
    ]
]);

// 2. Add attachments
$pdfBuilder = FileAttachmentBuilder::fromFile('/reports/project-report.pdf');
$excelBuilder = FileAttachmentBuilder::fromFile('/reports/data.xlsx');

MicrosoftGraph::attachments()
    ->forMessage('[email protected]', $message['id'])
    ->addFile($pdfBuilder);

MicrosoftGraph::attachments()
    ->forMessage('[email protected]', $message['id'])
    ->addFile($excelBuilder);

// 3. Send the message
MicrosoftGraph::mail()->send($message['id']);

// Files larger than 3MB throw an exception
try {
    $builder = FileAttachmentBuilder::fromFile('/large-file.zip');
} catch (\InvalidArgumentException $e) {
    // Handle large file - use upload session instead
    // (Upload session not yet implemented in this package)
}

use PrasadChinwal\MicrosoftGraph\Exceptions\InvalidEmailException;
use PrasadChinwal\MicrosoftGraph\Exceptions\ConfigurationException;
use Illuminate\Http\Client\RequestException;

try {
    $user = MicrosoftGraph::users()->find('invalid-email');
} catch (InvalidEmailException $e) {
    // Handle invalid email format
    return response()->json(['error' => $e->getMessage()], 400);
} catch (ConfigurationException $e) {
    // Handle configuration issues
    Log::error('Microsoft Graph configuration error: ' . $e->getMessage());
    return response()->json(['error' => 'Service unavailable'], 503);
} catch (RequestException $e) {
    // Handle API request failures
    Log::error('Microsoft Graph API error: ' . $e->getMessage());
    return response()->json(['error' => 'External service error'], 502);
}

// If configuration is missing or invalid, a ConfigurationException will be thrown
// Example error messages:
// "Microsoft Graph configuration 'TENANT_ID' is not set. Please ensure MICROSOFT_GRAPH_TENANT_ID is set in your .env file."
// "Microsoft Graph configuration 'timezone' is invalid: Invalid timezone identifier"

$graph = new MicrosoftGraph();
$graph->clearTokenCache();

'timezone' => 'Europe/London',

$user = MicrosoftGraph::users()->find('[email protected]');

// Full IDE autocomplete support
$user->displayName;      // string
$user->accountEnabled;   // bool
$user->businessPhones;   // array
$user->interests;        // array|null

use Illuminate\Support\Facades\Http;

public function test_user_retrieval()
{
    Http::fake([
        'graph.microsoft.com/*' => Http::response([
            'value' => [
                [
                    'displayName' => 'Test User',
                    'mail' => '[email protected]',
                    // ... other fields
                ]
            ]
        ], 200)
    ]);

    $users = MicrosoftGraph::users()->get();

    $this->assertCount(1, $users);
    $this->assertEquals('Test User', $users->first()->displayName);
}
bash
php artisan vendor:publish --tag=microsoft-graph-config
bash
php artisan make:graph-event TeamMeetingEvent