PHP code example of graystackit / laravel-gdpr-compliance

1. Go to this page and download the library: Download graystackit/laravel-gdpr-compliance 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/ */

    

graystackit / laravel-gdpr-compliance example snippets


namespace App\Models;

use GraystackIt\Gdpr\Contracts\PersonalData;
use GraystackIt\Gdpr\Enums\RetentionMode;
use GraystackIt\Gdpr\Support\PersonalDataBlueprint;
use GraystackIt\Gdpr\Traits\HasConsentRecords;
use GraystackIt\Gdpr\Traits\HasPersonalData;
use GraystackIt\Gdpr\Traits\IsPersonalDataSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements PersonalData
{
    use HasPersonalData, IsPersonalDataSubject, HasConsentRecords;

    public function personalData(PersonalDataBlueprint $b): PersonalDataBlueprint
    {
        return $b
            // PII: anonymize AND export
            ->field('name')->anonymizeWith('name')->exportable()
            ->field('email')->anonymizeWith('email')->exportable()
            ->field('phone')->anonymizeWith('phone')->exportable()

            // PII internal: anonymize only, do NOT export
            ->field('password')
                ->anonymizeWith('static_text', ['value' => '[ANONYMIZED]'])

            // Non-PII metadata: export only, never touched
            ->field('created_at')->exportable()
            ->field('locale')->exportable()

            ->retention(
                mode: RetentionMode::Delete,
                gracePeriodDays: 7,  // 0 = immediate, max 30
            )
            ->processOrder(1000); // subject is processed last
    }
}

namespace App\Models;

use GraystackIt\Gdpr\Contracts\PersonalData;
use GraystackIt\Gdpr\Enums\RetentionMode;
use GraystackIt\Gdpr\Support\PersonalDataBlueprint;
use GraystackIt\Gdpr\Traits\HasPersonalData;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Order extends Model implements PersonalData
{
    use HasPersonalData;

    public function personalData(PersonalDataBlueprint $b): PersonalDataBlueprint
    {
        return $b
            ->field('shipping_address')->anonymizeWith('address')->exportable()
            ->field('billing_email')->anonymizeWith('email')->exportable()
            ->field('total')->exportable()
            ->field('created_at')->exportable()
            ->retention(
                mode: RetentionMode::LegalHold,
                legalHoldDays: 3650,              // 10 years
                legalBasis: '§ 147 AO — tax record retention',
            )
            ->processOrder(100); // children before subject
    }

    public function scopePersonalDataForSubject(Builder $query, Model $subject): Builder
    {
        return match (true) {
            $subject instanceof \App\Models\User => $query->where('user_id', $subject->getKey()),
            default => $query->whereRaw('1 = 0'),
        };
    }
}

'models' => [
    \App\Models\User::class,
    \App\Models\Order::class,
    \App\Models\Address::class,
    \App\Models\Comment::class,

    // Vendor models with external profile and scope
    \Vendor\Package\ExternalModel::class => [
        'profile' => \App\Gdpr\Profiles\ExternalProfile::class,
        'scope'   => \App\Gdpr\Scopes\ExternalScope::class,
    ],
],

use GraystackIt\Gdpr\Facades\GDPR;

// --- Deletion ---
$user->requestDeletion();            // schedule with grace period
$user->deleteImmediately();          // skip grace, process now
$user->cancelDeletion();             // cancel during grace

GDPR::isDeletionPending($user);      // bool
User::whereDeletionPending()->get(); // query scope
User::whereNotDeletionPending()->get();

// --- Export ---
$request = $user->requestExport();   // creates a GdprRequest

// Dispatch the export job manually or let the command do it:
\GraystackIt\Gdpr\Jobs\PreparePersonalDataExportJob::dispatch($request->id);

// --- Consent ---
use GraystackIt\Gdpr\Enums\ConsentPurpose;

$user->grantConsent(ConsentPurpose::Analytics, 'cookie_banner');
$user->withdrawConsent(ConsentPurpose::Marketing);
$user->hasConsent(ConsentPurpose::Analytics);  // bool
$user->consentStatus();                         // ['necessary' => true, 'analytics' => true, ...]

// --- Package inventory ---
GDPR::packageInventory(); // returns array from last scan, or null

'anonymizers' => [
    // ... built-in aliases
    'ssn' => \App\Gdpr\Anonymizers\SsnAnonymizer::class,
],

->retention(
    mode: RetentionMode::Delete,       // 'delete' | 'anonymize' | 'legal_hold'
    gracePeriodDays: 7,                // 0 = immediate, max 30 (DSGVO Art. 12(3))
    legalHoldDays: 3650,               // 

// In your auth logic
if (GDPR::isDeletionPending($user)) {
    // Block login, show banner, redirect, etc.
}

// Or as middleware on auth routes
Route::middleware('gdpr.no-deletion-pending')->group(function () {
    // ...
});

// Or as a query scope
User::whereNotDeletionPending()->where('email', $email)->first();

$user->grantConsent(ConsentPurpose::Analytics, 'cookie_banner');
$user->withdrawConsent(ConsentPurpose::Analytics, 'profile_settings');
$user->hasConsent(ConsentPurpose::Analytics); // latest action wins

// Block routes that dpr.consent:marketing')->group(function () {
    // Returns 451 Unavailable For Legal Reasons if consent is missing
});

// Necessary always passes
Route::middleware('gdpr.consent:necessary')->group(function () {
    // Always accessible
});

use GraystackIt\Gdpr\Events\PersonalDataErased;

Event::listen(PersonalDataErased::class, function ($event) {
    // $event->deletion->subject_type, $event->deletion->subject_id
    // Clean up Stripe, Mailchimp, S3 avatars, etc.
});

'notifications' => [
    'deletion_requested' => \App\Notifications\MyDeletionRequested::class,
    'deletion_cancelled' => false,  // disable this notification
    'deletion_completed' => null,   // use package default
    'export_ready' => null,
],

use Illuminate\Support\Facades\Schedule;

Schedule::command('gdpr:process-deletions')->daily();
Schedule::command('gdpr:cleanup-exports')->daily();
Schedule::command('gdpr:prune')->weekly();

$inventory = GDPR::packageInventory();
// Returns: ['generated_at' => '...', 'composer' => [...], 'npm' => [...]]

'retention' => [
    'audits_days' => 1095,
    'consents_days' => 1095,
    'policy_acceptances_days' => 1095,
    'notification_email_days' => 7,
],
bash
php artisan vendor:publish --tag=gdpr-config
php artisan vendor:publish --tag=gdpr-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=gdpr-lang