![]() ![]() Now the article’s slug property is being set on save. slug = $model->generateSlug($model->title) So let’s get started by defining a Sluggable trait with a simple method for generating a slug from a string. For example, Colin Viebrock’s Eloquent Sluggable There’s no point re-inventing the wheel! A Simple Trait Example If you are here wanting to incorporate a sluggable behaviour into your own app I’d suggest installing one of the many existing packages out there that will do this for you. ![]() To take a look at how we can use traits with our Eloquent models we’ll consider a real world example and look under the hood to see how Laravel enables us to boot traits.įor our example we’ll create a basic trait for adding a sluggable behaviour to models that generates SEO friendly URL slugs.īefore we continue, the following example is just to demonstrate a practical use of traits with Laravel. Laravel’s own SoftDeletes trait uses this bootable feature to add a global scope that allows us to soft delete a model. When using traits with Eloquent models, Laravel has a neat trick that boots the trait allowing us to hook into the Eloquent events. They also allow us to pick ‘n’ mix behaviours for classes in a way that class inheritance doesn’t. Any properties or methods of a trait become instantly available to any class we attach the trait to as if they were properties or methods of that class. ![]() They provide a way of horizontally sharing logic between classes. Traits are a useful means of writing DRY code. In this blog post we’ll take a look at using PHP traits with Laravel’s Eloquent models, hooking them up with events and making them configurable. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |