skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search