this is my laravel custom accessor which I am appending using
protected $appends = [leave_balances];
public function getLeaveBalancesAttribute() {
// some code
}
I want to pass a parameter when I am calling this accessor like this
public function getLeaveBalancesAttribute($parameter) {
// use $parameter here
}
$payslip = Payslip::find(1);
Log::debug($payslip->leave_balances("PARAMETER"));
I have searched and found that it is not possible. please can some one provide any solution to this I need to pass this parameter.
3
Answers
If you declare an Attribute, you can only use it like this (following your example:
What you (I think) want is
setLeaveBalancesAttribute
, so you can pass a value and do whatever you want with it:But, if you are using Laravel 9+, please do use the new way of defining attributes, it is better.
you dont append attribute unless you want it to act as an attribute,
you can just create a method since you are calling it like a method
in you Payslip model
then you can use it like
You can set the attribute
$appends
in the model where you have the accessor. Something like this:However, it will be in the most, I think in all, the responses or query you do with the model you declare it.
Another options is creating a single instance of the model using the
::find
method. For example:Here is the documentation reference: https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor