I have a model in my laravel application called Job that uses the display_name attribute. Because of this, I need all of the columns that make up the display name to be included in any query ran on the Job model.
It's unrealistic in my application to remember to include these columns in every query so I have included this piece of code in the boot function of my model to do just that:
static::addGlobalScope('display_name_fields', function (Builder $builder) {
$builder->addSelect(...)
->with([... , ...]);
});
The issue I'm running into now is when the Job model is called without a select in the query (to get all jobs), only the columns in the addSelect are grabbed from the database. For example, these statements will only get the columns in the addSelect:
Job::get(); Job::where(...)->get();
The only time the addSelect works as intended is if other columns are specified like this:
Job::select('column1')->where(...);
Similarly, if a select() is included in the boot function the display name works but every column is selected:
$builder->select()->addSelect...
How can I make sure these columns are included in every query on the Job model without always including every column?