Skip to content

Conversation

DarkGhostHunter
Copy link
Contributor

@DarkGhostHunter DarkGhostHunter commented Apr 30, 2023

What?

Allows the static array for Global Scopes to be restored by allowing to retrieve and set them all.

use Illuminate\Database\Eloquent\Model;

$scopes = Model::getAllGlobalScopes();

// Handle request..

Model::setAllGlobalScopes($scopes);

Why?

Because the current implementation of Global Scopes, by being static, has some problems on Laravel Octane:

  • Global Scopes list can bleed into other requests in Laravel Octane.
  • Global Scopes with dynamic names can cause memory leaks.

This only adds two new methods to retrieve and set ALL of the Global Scopes. This allows Laravel Octane to save the original list, and restore it before handling the next request, avoiding bleeding or memory leaks.

It doesn't fix the problem with modifying a Scope instance state. This should be documented on Laravel Octane by warning the developer that Scope instances are shared across requests and, if needed, these should be manually "reset" before the next:

use App\Models\Album;
use App\Scopes\ShowPrivatePhotos;
use Illuminate\Support\Facades\Event;
use Laravel\Octane\Events\RequestHandled;
 
/**
 * Register any other events for your application.
 */
public function boot(): void
{
    Event::listen(RequestHandled::class, function () {
        $privateScope = Album::getGlobalScope(ShowPrivatePhotos::class);

        $privateScope->removeAuthenticatedUserID();
    });
}

BC?

Nope, only additive.

@taylorotwell taylorotwell merged commit f8dd01a into laravel:10.x May 1, 2023
milwad-dev pushed a commit to milwad-dev/framework that referenced this pull request May 12, 2023
* [10.x] Adds ability to restore/set Global Scopes

* Update HasGlobalScopes.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
@DarkGhostHunter DarkGhostHunter deleted the feat/set-get-global-scopes branch June 27, 2023 02:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants