0

Is possible to attach a custom attribute when retrieving a model in laravel?.

The problem is that I need to return some data that is not in the database along the info from the database. I've been doing it manually but I guess that there might be a way to do it in the model.

Example: I have an application table. Each application contains a folder with documents with the same application id. I need to attach the amount of files the folder that correspond to each application.

This is what I do:

$application = Application::get();
$application = $application->map(function($a){
    $a->files = $this->getFiles($a->id); // This gets the amount of files
    return $a;
})

Is there some way to do it in the model in a way that $application->files is already contained in $application when doing Application::get()

2
  • 1
    You"re looking for protected $appends = [] property on the model. Commented Oct 3, 2018 at 12:12
  • @JagjeetSingh it retrieves the files on the server from a folder with the same id as the application. but I did it using the answers and the $appends prop. Thanks Commented Oct 3, 2018 at 12:20

2 Answers 2

2
class User extends Model
{
    public function getFooBarAttribute()
    {
        return "foobar";
    }
}

And access to that attribute like:

$user->foo_bar;

or like,

$user->fooBar;

More detailed documentation; https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

Sign up to request clarification or add additional context in comments.

Comments

1

in the Application model

public function getFilesAttribute()
{
    return 'lala'; // return whatever you need;
}

now application model has an attribute named files.

$application->files // returns lala.

example code.

$applications = Application::get();
$application_files = applications->map->files;

official documentation https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

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.