PHP code example of kyzegs / laravel-eloquent-embeddables
1. Go to this page and download the library: Download kyzegs/laravel-eloquent-embeddables 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/ */
kyzegs / laravel-eloquent-embeddables example snippets
use Kyzegs\EloquentEmbeddables\EmbeddableModel;
final class Address extends EmbeddableModel
{
protected $fillable = [
'street',
'city',
'postal_code',
'country',
];
protected function casts(): array
{
return [
'verified' => 'boolean',
];
}
public function fullAddress(): string
{
return trim("{$this->street}, {$this->postal_code} {$this->city}, {$this->country}");
}
}
use Illuminate\Database\Eloquent\Model;
use Kyzegs\EloquentEmbeddables\Casts\EmbeddableCast;
final class User extends Model
{
protected function casts(): array
{
return [
'address' => EmbeddableCast::using(Address::class, nullable: true),
];
}
}
use Illuminate\Database\Eloquent\Model;
use Kyzegs\EloquentEmbeddables\Casts\EmbeddableCast;
final class User extends Model
{
protected function casts(): array
{
return [
'address' => EmbeddableCast::using(
Address::class,
prefix: 'address_',
attributes: ['street', 'city', 'postal_code', 'country', 'verified'],
nullable: true,
),
];
}
}
$user->address = null;
$user->save(); // sets every mapped column to null
use Illuminate\Database\Eloquent\Model;
use Kyzegs\EloquentEmbeddables\Concerns\HasEmbeddables;
final class User extends Model
{
use HasEmbeddables;
// ...casts() as above
}