Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Anonymous Global Scopes does not apply after $model->refresh() #45091

Open
amshehzad opened this issue Nov 25, 2022 · 4 comments
Open

Anonymous Global Scopes does not apply after $model->refresh() #45091

amshehzad opened this issue Nov 25, 2022 · 4 comments

Comments

@amshehzad
Copy link

amshehzad commented Nov 25, 2022

  • Laravel Version: 9.41.0
  • PHP Version: 8.1.2
  • Database Driver & Version:

Description:

When a refresh method is called on a model, the Anonymous Global Scope does applied on model

Steps To Reproduce:

In User Model, apply a global scope to select a column like this:

 protected static function booted()
 {
     static::addGlobalScope(fn(Builder $builder) => $builder
         ->when(
             is_null($builder->getQuery()->columns),
             fn(Builder $builder) => $builder->addSelect('*')
         )
         ->selectRaw("34 AS age")
     );
 }

Then in UserController:

$user = \App\Models\User::first();
$user->age;  // 34
$user->refresh();
$user->age;  // null
@WendellAdriel
Copy link

WendellAdriel commented Nov 25, 2022

I think the same can be achieved using the $attributes array in the model instead of the global scope or am I missing something @amshehzad?

@amshehzad
Copy link
Author

amshehzad commented Nov 25, 2022

@WendellAdriel Yes that would be right if I had the exact same attribute. I just added it here as an example,
Actual code was this:

static::addGlobalScope(fn(Builder $builder) => $builder
            ->when(
                is_null($builder->getQuery()->columns),
                fn(Builder $builder) => $builder->addSelect('*')
            )
            ->selectRaw('IFNULL((SELECT SUM(amount) FROM leave_transactions WHERE user_id = users.id), 0) AS leave_balance')
        );

@WendellAdriel
Copy link

WendellAdriel commented Nov 25, 2022

@amshehzad oh got it!
Can’t you do that with an $appends attribute using the relation between the two models?

@github-actions
Copy link

github-actions bot commented Nov 28, 2022

Thank you for reporting this issue!

As Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.
If possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants