0

I am using laravel and I want to add dynamic custom attribute in controller

I know there is a way like this

      public function getFullNameAttribute()
        {
            return $this->first_name.' '.$this->last_name;
        }

now you can get full name as:

    $user = User::find(1);
    $user->full_name;

but it is in Model I want to declare custom att in controller is it possible?

5
  • Why would you want to do it in the controller? It makes more sense in the model and this 'magic method' is only supported in the Model Commented Aug 1, 2020 at 3:47
  • @Christophe Hubert because I want to pass dynamic att for each record ( for example related Items ) and I find related Items in controller Commented Aug 1, 2020 at 3:49
  • 2
    I would recommend to still keep it in the Model and then use a custom accessor that accept arguments: getFullNameWithExtra($extra) {...} Commented Aug 1, 2020 at 3:53
  • why would a controller need "attributes"? Commented Aug 1, 2020 at 4:17
  • I'm not sure you're making your use case clear here. As you mentioned, this can be done in the model. Can you provide an example of what you're trying achieve? Commented Aug 1, 2020 at 6:30

1 Answer 1

2

Why not in model? Eloquent has a great feature called “Accessors”. The feature allows you to add custom fields to models that don’t exist on the model or in the table.

function getFullNameAttribute() {
    return sprintf('%s %s', $this->first_name, $this->last_name);
}

Now you have access to a full_name attribute on the model, same as you mentioned:

$user = User::find(1);
$user->full_name;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.