PHP code example of sowailem / fieldguard

1. Go to this page and download the library: Download sowailem/fieldguard 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/ */

    

sowailem / fieldguard example snippets


use Sowailem\FieldGuard\Models\FieldGuardRule;

FieldGuardRule::create([
    'model_class' => 'App\Models\User',
    'field_name' => 'salary',
    'read_policy' => ['roles' => ['admin', 'hr'], 'allow_self' => true],
    'write_policy' => ['roles' => ['admin']],
    'mask' => 'PROTECTED',
    'is_active' => true,
]);

'automatic_enforcement' => true,

use Sowailem\FieldGuard\Facades\FieldGuard;

public function view(User $user)
{
    // Returns the model attributes as an array, filtered by security rules
    return FieldGuard::apply($user, auth()->user());
}

public function toArray($request)
{
    return FieldGuard::apply($this->resource, $request->user());
}

// Laravel 11+ example in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'fieldguard' => \Sowailem\FieldGuard\Middleware\EnforceFieldSecurityMiddleware::class,
    ]);
})

Route::put('/users/{user}', [UserController::class, 'update'])
    ->middleware('fieldguard:App\Models\User');

namespace App\Security;

use Sowailem\FieldGuard\Contracts\PolicyResolver;
use Illuminate\Database\Eloquent\Model;

class MyCustomResolver implements PolicyResolver
{
    public function resolve(array $policy, Model $model, $user): bool
    {
        // Your custom logic here
        return true;
    }
}

'resolver' => \App\Security\MyCustomResolver::class,

'api' => [
    'enabled' => true,
    'prefix' => 'field-guard',
    'middleware' => ['api', 'auth:sanctum'],
],

use Illuminate\Support\Facades\Gate;

Gate::define('manage-field-guard', function ($user) {
    return $user->isAdmin(); // Your authorization logic
});
bash
php artisan migrate
bash
php artisan fieldguard:clear-cache
bash
php artisan db:seed --class="Sowailem\FieldGuard\Database\Seeders\FieldGuardRuleSeeder"
bash
php artisan vendor:publish --tag="fieldguard-routes"