Save third api keys in databases

Latarips
Latarips

The Illuminate\Support\Facades\Crypt class in Laravel provides simple yet powerful methods for securely encrypting and decrypting sensitive data within your application. The encryptString method allows you to swiftly encrypt a text string securely.

To utilize encryptString, ensure you import the Crypt class at the beginning of your PHP file:

use Illuminate\Support\Facades\Crypt;

Once the class has been imported, you can employ encryptString in the following manner:

$record->value = Crypt::encryptString($data['example_api_key'])
$record->save();

Another implementation example using Filament 3 and an Action in a table, includes a possible display of the value.

use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Crypt;

public static function table(Table $table): Table
{
    return $table
        ->columns([
            //Other Columns CODE...
            Tables\Columns\TextColumn::make('value')
                ->formatStateUsing(function ($state, Model $record) {
                    return $record->type == 'api_key' ? ($state ? "**********" : 'Empty' ) : $state;
                })
        ])
        ->filters([
            //Filters CODE...
        ])
        ->actions([
            Tables\Actions\Action::make('edit')
            ->fillForm(fn (Model $record): array => [
                'value' => $record->value,
            ])
            ->action(function (array $data, Model $record): void {
                if($record->type == 'api_key'){
                    $record->value = Crypt::encryptString($data['value']);
                    $record->save();
                }else{
                    $record->value = $data['value'];
                    $record->save();
                }
            })            
        ])
        ->bulkActions([
            //BulcActions CODE...
        ])
}

The encryptString method will take the original text and encrypt it, returning an encrypted string that can be securely stored in your database or any other necessary location.

Remember, to decrypt the encrypted string, you can use the decryptString method in the same way:

$decryptedText = Crypt::decryptString($encryptedText);

One last tip: to display in tables that you have a saved token, instead of showing the encrypted text, you can display text with asterisks or some other glyph. This example is implemented using TextColumn of Filement 3.

use Filament\Tables;

Tables\Columns\TextColumn::make('value')
    ->formatStateUsing(function ($state, Model $record) {
        return $record->type == 'api_key' ? ($state ? "**********" : 'Empty' ) : $state;
    })
#encrypt #decrypt