The Laravel Custom Casts package by Vladimir Ković enables you to make your own custom cast types in Eloquent models:
Laravel custom casts works similarly to Laravel attribute casting, but with our custom defined logic (in separated class). Beside casting to our complex types, this package gives us the ability to listen and react to underlying model events.
Here’s an example model utilizing a custom cast class:
1namespace App; 2 3use App\CustomCasts\NameCast; 4use Illuminate\Database\Eloquent\Model; 5use Vkovic\LaravelCustomCasts\HasCustomCasts; 6 7class User extends Model 8{ 9 use HasCustomCasts;10 11 protected $casts = [12 'is_admin' => boolean // <-- Laravel default cast type13 'name' => NameCast::class // <-- Our custom cast class (follow section below)14 ];15}
With the above model in mind, here’s an example of the custom cast class:
1namespace App\CustomCasts; 2 3use Vkovic\LaravelCustomCasts\CustomCastBase; 4 5class NameCast extends CustomCastBase 6{ 7 public function setAttribute($value) 8 { 9 return ucwords($value);10 }11 12 public function castAttribute($value)13 {14 return $this->getTitle() . ' ' . $value;15 }16 17 protected function getTitle()18 {19 return ['Mr.', 'Mrs.', 'Ms.', 'Miss'][rand(0, 3)];20 }21}
The $value
in the setAttribute()
method is the raw database value we want to store. This package also enables you to handle model events and react to those events.
You can learn more about this package, get full installation instructions, and view the source code on GitHub at vkovic/laravel-custom-casts.
0 comments:
Post a Comment
Thanks