Search code examples
laraveleloquentquerying

Add column to Eloquent


I'm trying to get an Eloquent collection with the next line:

Document::with('more_information')->anyScope()->get()

I'm getting a collection with 20 "columns", but I want to add another one to format a date in order to easily interact with other components instead of format the date in each component.

To add this column I can rewrite the 21 column names and write more lines to get the collections that invoke with my with...but that doesn't look good...

Is there a way to simply to add my 21st column without rewrite the other 20?

I read something about addSelect, but in my code it ignores my 20 first columns


Solution

  • Finally got it, it works doing the next:

    Document::with('more_information')->anyScope()->get('*',<aditional columns>)
    

    Update: Looking for another more suitable way to get my task done, I found a mixture between accessors and the Model property $appends

    Using next script I'm able to retrieve my collection with a custom column. It's important to mention that if you don't use $appends, the accessor works well but it's not returned within the array. It's not recommended to use a lot of times $appends because it affects in a negative way the performance

    class Trabajador extends Model {
    
        protected $appends = ["fullName"];
    
        public function getFullNameAttribute() {
             return $this->attributes['nombre'] . $this->attributes['apellidos'];
        }
    }