PHP code example of yassinedabbous / laravel-file-cast

1. Go to this page and download the library: Download yassinedabbous/laravel-file-cast 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/ */

    

yassinedabbous / laravel-file-cast example snippets


use YassineDabbous\FileCast\FileCast;

class User extends Model
{
	# Laravel<11.x
    protected $casts = [
        'avatar' => FileCast::class,                    // use default disk
        'avatar' => FileCast::class.':s3,photo.png',    // use "S3" disk and "photo.png" as default value
    ];

    # OR

    # Laravel >=11.x
    public function casts(): array
    {
        return [
            'avatar' => FileCast::class,                                    // use default disk
            'avatar' => FileCast::using(disk: 's3', default: 'photo.png'),  // use S3 disk and "photo.png" as default value
            'avatar' => FileCast::using(disk: $this->disk_column),          // use column value as a disk name
        ];
    }
}

class Post extends Model
{
    ... 
    
	/** Set a disk for each column */
    public function disks(): array {
        return [
            'photo' => $this->disk_column,              # use column value as a disk
            'video' => $migrated ? 's3' : 'public',     # conditional disk 
        ];
    }

    ...
}

$model->avatar = $request->avatar;
$model->save();

Model::create( $request->validated() );
// or
$model->update( $request->validated() );

$model->avatar = '/full/path/to/local/file.ext';

$model->avatar; // /disk/folder/file.ext

$model->avatar = 'https://via.placeholder.com/150/FF0000/FFFFFF';

$model->avatar; // /disk/folder/file.png

$model->avatar = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAAWSURBVBhXY/zPwABEDAxMIIKBgYEBAB8XAgIcVRdpAAAAAElFTkSuQmCC';

$model->avatar; // /disk/folder/file.png

$model->avatar = '{"key1": "value1"}';

$model->avatar; // /disk/folder/file.json

# Store associative array as *json* file
# => folder/file.json
$model->avatar = ['key1' => 'value1', 'key2' => 'value2'];

# Store multi list array as *csv* file
# => folder/file.csv
$model->avatar = [
            ['value1', 'value2', 'value3'],
            ['value1', 'value2', 'value3'],
            ['value1', 'value2', 'value3'],
        ];

$model->avatar = null; # == $model->avatar->delete();

use Illuminate\Support\Facades\Storage;

# using Laravel Storage Facade:
Storage::disk('disk')->url(path: 'path.ext');
Storage::disk('disk')->json(path: 'path.ext');
Storage::disk('disk')->put(path: 'path.ext', contents: 'data');
Storage::disk('disk')->temporaryUrl(path: 'path.ext', expiration: now()->addMinutes(5));
...

# using File Cast
$model->avatar->url();
$model->avatar->json();
$model->avatar->put(contents: 'data');
$model->avatar->temporaryUrl(expiration: now()->addMinutes(5));
...


$model->avatar->toBase64();             # Base64 string: 'iVBORw0KGgoAAAANS...'
$model->avatar->toBase64URI();          # Base64 URI: 'data:image/png;base64,iVBORw0KGgoAAAANS...'


$model->avatar->toArray();              # returns *json* and *csv* file's content as array


$model->avatar; 
# 'old_file.png';

$model->avatar = $newFileUploaded;
# 'old_file.png' deleted!

use YassineDabbous\FileCast\HasFileCast;

class User extends Model
{
    use HasFileCast;
    ...
}

$model->avatar = NULL;                                      # Delete the file without updating table.
$model->avatar->delete();                                   # Delete the file without updating table.
$model->avatar->delete(persist: TRUE);                      # Delete the file & save changes to DB.

$model->avatar; 
# 'folder/old_file.png';

$model->avatar = '@new_folder/new_file.png';                           # Move the file without updating table. (path should start with "@")
$model->avatar->move(to: 'new_folder/new_file.png');                   # Move the file without updating table.
$model->avatar->move(to: 'new_folder/new_file.png', persist: TRUE);    # Move the file & save changes to DB.

use YassineDabbous\FileCast\FileField;
 
FileField::macro('resize', function ($with, $height) {
    $image = imagecreatefrompng($this->path());
    $imgResized = imagescale($image , $with, $height);
    imagejpeg($imgResized, $this->path()); 
    return $this;
});
 
# resize uploaded image 
$model->photo = $request->file('image');
$model->photo->resize(500, 500);



return [
    /** Default value when no file uploaded. */
    'default' => env('FILE_CAST_DEFAULT'),

    /** Default storage disk */
    'disk' => env('FILE_CAST_DISK'),

    /** Default storage folder. If NULL, the Model's table name will be used. */
    'folder' => env('FILE_CAST_FOLDER'),

    /** Automatically clean files on column value updated. */
    'auto_delete' => env('FILE_CAST_AUTO_DELETE', true),

    /** Serialize attribute to full URL. */
    'serialize_to_full_url' => env('FILE_CAST_SERIALIZE_TO_FULL_URL', true),
];