PHP code example of andydefer / laravel-casts

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

    

andydefer / laravel-casts example snippets




namespace App\Models;

use AndyDefer\LaravelCasts\Casts\MoneyCast;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $casts = [
        'price' => MoneyCast::class,
    ];
}

// Création d'un produit
$product = new Product();
$product->price = 12.34;  // Stocké comme 1234 en base

// Récupération
echo $product->price;      // Affiche 12.34

// Valeurs nulles
$product->price = null;    // Stocké comme NULL en base

$product->price = 12.345;  // Stocké comme 1235 (arrondi)
$product->price = 0.055;   // Stocké comme 6 (arrondi supérieur)

$product->price = -5.00;   // Stocké comme -500
$product->price = -0.50;   // Stocké comme -50

// Recherche par prix exact (en centimes)
Product::where('price', 1234)->get();  // Prix = 12.34
Product::where('price', '>', 1000)->get();  // Prix > 10.00



namespace App\Models;

use AndyDefer\LaravelCasts\Casts\JsonCast;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'preferences' => JsonCast::class,
    ];
}

// Création d'un utilisateur
$user = new User();
$user->preferences = [
    'theme' => 'dark',
    'notifications' => true,
    'language' => 'fr'
];
$user->save();  // Stocké comme '{"theme":"dark","notifications":true,"language":"fr"}'

// Récupération
$preferences = $user->preferences;
echo $preferences['theme'];  // Affiche 'dark'

// Valeurs nulles
$user->preferences = null;   // Stocké comme NULL en base

$user->preferences = '{"theme":"light"}';  // Stocké tel quel

$user->preferences = '{invalid json';  // Retourne null

$user->preferences = '"just a string"';  // Retourne []

// Création d'une colonne pour MoneyCast
Schema::table('products', function (Blueprint $table) {
    $table->integer('price')->nullable();  // Stocke les centimes
});

// Création d'une colonne pour JsonCast
Schema::table('users', function (Blueprint $table) {
    $table->json('preferences')->nullable();  // Type JSON recommandé
    // ou
    $table->text('preferences')->nullable();  // Alternative pour vieilles versions MySQL
});



namespace App\Models;

use AndyDefer\LaravelCasts\Casts\MoneyCast;
use AndyDefer\LaravelCasts\Casts\JsonCast;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $casts = [
        'subtotal' => MoneyCast::class,
        'tax' => MoneyCast::class,
        'total' => MoneyCast::class,
        'shipping_address' => JsonCast::class,
        'items' => JsonCast::class,
    ];
}

// Utilisation
$order = Order::create([
    'subtotal' => 99.99,
    'tax' => 20.00,
    'total' => 119.99,
    'shipping_address' => [
        'street' => '123 Main St',
        'city' => 'Paris',
        'zip' => '75001'
    ],
    'items' => [
        ['id' => 1, 'name' => 'Product A', 'price' => 49.99, 'quantity' => 2],
        ['id' => 2, 'name' => 'Product B', 'price' => 50.00, 'quantity' => 1],
    ]
]);

// Requêtes
$expensiveOrders = Order::where('total', '>', 10000)->get();  // > 100.00 €



namespace App\Models;

use AndyDefer\LaravelCasts\Casts\JsonCast;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'settings' => JsonCast::class,
        'metadata' => JsonCast::class,
    ];
    
    // Accesseur avec valeur par défaut
    public function getSetting(string $key, mixed $default = null): mixed
    {
        return $this->settings[$key] ?? $default;
    }
    
    // Mutateur pour mise à jour partielle
    public function setSetting(string $key, mixed $value): self
    {
        $settings = $this->settings ?? [];
        $settings[$key] = $value;
        $this->settings = $settings;
        return $this;
    }
}

// Utilisation
$user = User::find(1);
$user->setSetting('theme', 'dark');
$user->setSetting('notifications', ['email' => true, 'sms' => false]);
$user->save();

echo $user->getSetting('theme', 'light');  // 'dark'



namespace App\Models;

use AndyDefer\LaravelCasts\Casts\MoneyCast;
use AndyDefer\LaravelCasts\Casts\JsonCast;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $casts = [
        'price' => MoneyCast::class,
        'attributes' => JsonCast::class,
    ];
    
    // Scope pour filtrage JSON
    public function scopeWithAttribute($query, string $key, mixed $value)
    {
        return $query->whereRaw("JSON_EXTRACT(attributes, '$.{$key}') = ?", [$value]);
    }
}

// Utilisation
$product = Product::create([
    'name' => 'T-Shirt',
    'price' => 29.99,
    'attributes' => [
        'color' => 'blue',
        'size' => 'L',
        'material' => 'cotton',
        'stock' => 50
    ]
]);

// Recherche par attribut JSON
$blueTshirts = Product::withAttribute('color', 'blue')->get();

// Mise à jour partielle
$product = Product::find(1);
$attributes = $product->attributes;
$attributes['stock'] = 45;
$product->attributes = $attributes;
$product->save();