how can I pass parameter to laravel getAttribute when I am appending it

1.7k Views Asked by At

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

There are 3 best solutions below

6
matiaslauriti On

If you declare an Attribute, you can only use it like this (following your example:

protected $appends = ['leave_balances'];

public function getLeaveBalancesAttribute()
{
    return 'Hi!';
}

$payslip = Payslip::find(1);

$value = $payslip->leave_balances;

dd($value); // This will output string(Hi!)

What you (I think) want is setLeaveBalancesAttribute, so you can pass a value and do whatever you want with it:

public function setLeaveBalancesAttribute($parameter)
{
    return $parameter.' Yes!';
}

$payslip = Payslip::find(1);

$payslip->leave_balances = 'It works!';

dd($payslip->leave_balances); // This will output string(It works! Yes!)

But, if you are using Laravel 9+, please do use the new way of defining attributes, it is better.

2
silver On

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

public function leaveBalances( $params ) { 
    return $params
}

then you can use it like

$payslip = Payslip::find(1);
$payslip->leaveBalances("PARAMETER") // which output PARAMETER
0
Álvaro On

You can set the attribute $appends in the model where you have the accessor. Something like this:

protected $appends = ['the name of accessor'];

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:

$model_instance = Model::find($id);
$attribute = $model_instance->attribute;

Here is the documentation reference: https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor