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 = '"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
});