So, today I learned a small
Laravel / Eloquent feature , which is practically not described and only briefly mentioned in the freymovik’s documentation.
Go to TL; DR if you just want to see this feature.You may already know that you can add static
boot () methods to
Eloquent models that will be executed when it is loaded. This can be used, for example, by attaching to model events, if necessary. For example, you can organize an email notification every time a new user is created (a
bad example ), but you could describe it like this:
class User extends Eloquent { public static function boot() { parent::boot(); static::created(function($user) {
But what if you want to put it with a
trait ?
Consider this scenario; need to organize a search in a range of models. Of course, you can create a new
SearchableModel class, inheriting it from
Eloquent \ Model , but I would like to write it in such a way that the functionality can be easily transferred to other projects without being tied to a specific application. The trait here fits better, because it is easily portable and relatively unobtrusive, connecting which you get additional functionality that can be easily redefined.
')
So, I created SearchableTrait.
trait SearchableTrait { public function search($query) {
Quite simply, for now, we call the
$ model-> search ('query') method, which returns models that match the query criteria.
However, instead of directly searching the database, I plan to use a third-party search by application (
if you are interested, elasticsearch ), which uses its own indexing, which requires adjusting the index of each row manually.
But where should I paste this code?
I could put it in the model's
boot () method, but there it can be overwritten, thereby disrupting my search and destroying any chance of being reused.
Tl; DRThe guys from Laravel clearly provided for how to load your traits by defining a special method, as in the Eloquent-model, for example:
trait SearchableTrait { public function search($query) {
Thus, here there is a little classic magic
Eloquent . If you have a static method in Tray, which is called the
boot [ NameOfTrait] principle, then it will be executed in the same way as the static
boot () method of the model. What a convenient place to register events of your model.
An example in the documentation for Laravel, implements this trick when
registering a global scop , to intercept all running queries, with a soft deletion of models.
Of course, besides this feature, there are other good ways to achieve the same result, but it is always pleasant to keep poorly documented subtleties in your arsenal to use them if necessary.