Add a custom attribute when retrieving a model

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()

Upvotes: 0

Views: 56

Answers (2)

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

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

Upvotes: 1

mutas
mutas

Reputation: 359

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

Upvotes: 2

Related Questions