Checking If A Mutator or Accessor Has Been Set
There are lots of hidden gems in Laravel Model’ code base. Today, while going through the code base of Illuminate\Database\Eloquent\Model class, I found that we can check if a mutator or accessor has been set for a model or not.
Illuminate\Database\Eloquent\Model class use a trait called HasAttributes, if you open this class trait you will find there are two methods used in this trait hasSetMutator and hasGetMutator.
Let’s see how we can use them.
In an Eloquent model, you can set mutator or accessor on your model properties. You might want to check if a mutator or accessor exists for a given property.
For example, we have a Product model with property called
sku and we want to check that if
sku property has an accessor.
// Grab the model by its primary key $product = Product::find(1); // Return boolean value depending on the existance of accessor echo $product->hasSetMutator('sku');
Above code example will return a boolean
false depending on the existance of accessor.
We can run a check on the mutator as well for same property
// Grab the model by its primary key $product = Product::find(1); // Return boolean value depending on the existance of accessor echo $product->hasGetMutator('sku');
That’s it. Hope this will help you.