Just wanted to know if it is possible to eager-load a defined accessor in Laravel Repository. I am currently using this l5-repository package and Laravel 5.4.
In my UserInfo.php
model, I have this function
public function getFullNameAttribute()
{
return ucfirst($this->first_name . " ". $this->last_name);
}
Then I am trying to eager load that accessor in my controller like this.
$user_infos = $this->repository->with('full_name')->all();
// or $user_infos = $this->repository->with('getFullNameAttribute')->all();
return response()->json([ 'data' => $user_infos ]);
I know that it is not gonna work. I am just looking for a similar way to add my accessor full_name
in my collection. So I don't need to concatenate in my front end. So my expected result would be
{
id : 1,
first_name : "Sample fname",
last_name : "Sample lname",
.....
.....
full_name : "Sample fname Sample lname",
}
Use $appends
in your model UserInfo.php
protected $appends = ['full_name'];
This will append this custom field in your collection.
Then you can see it here :
$user_infos = UserInfo::all();
$user_infos->toJson();
You can see the appended accessor in the json.