PHPackages                             tonysm/globalid-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tonysm/globalid-laravel

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tonysm/globalid-laravel
=======================

Identify app models with a URI. Inspired by the globalid gem.

1.5.0(1mo ago)45101.6k—8.5%3[1 issues](https://github.com/tonysm/globalid-laravel/issues)1MITPHPPHP ^8.2CI passing

Since Aug 23Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/tonysm/globalid-laravel)[ Packagist](https://packagist.org/packages/tonysm/globalid-laravel)[ Docs](https://github.com/tonysm/globalid-laravel)[ RSS](/packages/tonysm-globalid-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (12)Versions (18)Used By (1)

[![GlobalIds Laravel](/art/globalids-laravel-logo.svg)](/art/globalids-laravel-logo.svg)

 [![](https://github.com/tonysm/globalid-laravel/workflows/run-tests/badge.svg)](https://github.com/tonysm/globalid-laravel/workflows/run-tests/badge.svg) [![Total Downloads](https://camo.githubusercontent.com/4b0ee2ff42c064615a4700cbd95abf90f5f48b982526dcedb50b9f315f2d197d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f6e79736d2f676c6f62616c69642d6c61726176656c)](https://packagist.org/packages/tonysm/globalid-laravel) [![License](https://camo.githubusercontent.com/b452fb036dd7778ca836598a0290b5f957249d760a20a6bd154febc47512875f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f746f6e79736d2f676c6f62616c69642d6c61726176656c)](https://packagist.org/packages/tonysm/globalid-laravel)

Introduction
============

[](#introduction)

Identify app models with a URI.

A Global ID is an app wide URI that uniquely identifies a model instance:

```
gid://YourApp/Some\\Model/id

```

This is helpful when you need a single identifier to reference different classes of objects.

One example is storing model references in places where you cannot enforce constraints or cannot make use of the convenient Eloquent relationships, such as storing model references in a rich text content field. We need to reference a model object rather than serialize the object itself. We can pass a Global ID that can be used to locate the model when it's time to render the rich text content. The rendering doesn't need to know the details of model naming and IDs, just that it has a global identifier that references a model.

Another example is a drop-down list of options, consisting of both Users and Groups. Normally we'd need to come up with our own ad hoc scheme to reference them. With Global IDs, we have a universal identifier that works for objects of both classes.

### Inspiration

[](#inspiration)

Heavily inspired by the [globalid gem](https://github.com/rails/globalid).

Installation
------------

[](#installation)

Via Composer:

```
composer require tonysm/globalid-laravel

```

Usage
-----

[](#usage)

Add the `HasGlobalIdentification` trait to any Eloquent model (or any class with a `find($id)`, `findMany($ids): Collection` static methods, and a `getKey()` instance method):

```
use Tonysm\GlobalId\Models\HasGlobalIdentification;

class Person extends Model
{
    use HasGlobalIdentification;
}
```

Then you can create GlobalIds and SignedGlobalIds like so:

```
$personGid = Person::find(1)->toGlobalId();
# => Tonysm\GlobalId\GlobalId {#5010}

$personGid->toString();
# => "gid://laravel/App%5CModels%5CPerson/1"

# Returns a URL-safe base64 encoded version of the SGID...
$personGid->toParam();
# => "Z2lkOi8vbGFyYXZlbC9BcHAlNUNNb2RlbHMlNUNQZXJzb24vMQ"

Tonysm\GlobalId\Facades\Locator::locate('gid://laravel/App%5CModels%5CPerson/1');
# => App\Models\Person {#5022 id:1...

# You can also pass the base64 encoded to it and it will just work...
Tonysm\GlobalId\Facades\Locator::locate('Z2lkOi8vbGFyYXZlbC9BcHAlNUNNb2RlbHMlNUNQZXJzb24vMQ');
# => App\Models\Person {#5022 id:1...

# You can also call the locate method on the GlobalId object...
$personGid->locate();
# => App\Models\Person {#5022 id:1...
```

You may customize the location logic using a [custom locator](#custom-locators).

### Signed Global IDs

[](#signed-global-ids)

For added security GlobalIDs can also be signed to ensure that the data hasn't been tampered with.

```
$personSgid = Person::find(1)->toSignedGlobalId();
# => Tonysm\GlobalId\SignedGlobalId {#5005}

$personSgid = Person::find(1)->toSgid();
# => Tonysm\GlobalId\SignedGlobalId {#5026}

$personSgid->toString();
# => "BAhJIh5naWQ6Ly9pZGluYWlkaS9Vc2VyLzM5NTk5BjoGRVQ=--81d7358dd5ee2ca33189bb404592df5e8d11420e"

Tonysm\GlobalId\Facades\Locator::locateSigned($personSgid);
# => App\Models\Person {#5009 id: 1, ...

# You can also call the locate method on the SignedGlobalId object...
$personSgid->locate();
# => App\Models\Person {#5022 id:1...
```

**Expiration**

Signed Global IDs can expire some time in the future. This is useful if there's a resource people shouldn't have indefinite access to, like a share link.

```
$expiringSgid = Document::find(5)->toSgid([
    'expires_at' => now()->addHours(2),
    'for' => 'sharing',
]);
# => Tonysm\GlobalId\SignedGlobalId {#5026}

# Within 2 hours...
Tonysm\GlobalId\Facades\Locator::locateSigned($expiringSgid->toString(), [
    'for' => 'sharing',
]);
# => App\Models\Document {#5009 id: 5, ...

# More than 2 hours later...
Tonysm\GlobalId\Facades\Locator::locateSigned($expiringSgid->toString(), [
    'for' => 'sharing',
]);
# => null
```

**An auto-expiry of 1 month is set by default.** You can override this default by passing a expiration resolver Closure from any Service Provider boot method. This resolver will get called every time a SGID is created:

```
SignedGlobalId::useExpirationResolver(() => now()->addMonths(3));
```

This way any generated SGID will use that relative expiry.

It's worth noting that *expiring SGIDs are not idempotent* because they encode the current timestamp; repeated calls to `to_sgid` will produce different results. For example:

```
Document::find(5)->toSgid()->toString() == Document::find(5)->toSgid()->toString()
# => false
```

You need to explicitly pass `['expires_at' => null]` to generate a permanent SGID that will not expire,

```
# Passing a false value to either expiry option turns off expiration entirely.
$neverExpiringSgid = Document::find(5)->toSgid(['expires_at' => null]);
# => Tonysm\GlobalId\SignedGlobalId {#5026}

# Any time later...
Tonysm\GlobalId\Facades\Locator::locateSigned($neverExpiringSgid);
# => App\Models\Document {#5009 id: 5, ...
```

**Purpose**

You can even bump the security up some more by explaining what purpose a Signed Global ID is for. In this way evildoers can't reuse a sign-up form's SGID on the login page. For example:

```
$signupPersonSgid = Person::find(1)->toSgid(['for' => 'signup_form']);
# => Tonysm\GlobalId\SignedGlobalId {#5026}

Tonysm\GlobalId\Facades\Locator::locateSigned($signupPersonSgid, ['for' => 'signup_form']);
# => App\Models\Person {#5009 id: 1, ...

Tonysm\GlobalId\Facades\Locator::locateSigned($signupPersonSgid, ['for' => 'login']);
# => null
```

### Locating many Global IDs

[](#locating-many-global-ids)

When needing to locate many Global IDs use `Tonysm\GlobalId\Facades\Locator->locateMany` or `Tonysm\GlobalId\Facades\Locator::locateManySigned()` for Signed Global IDs to allow loading Global IDs more efficiently.

For instance, the default locator passes every `$modelId` per `$modelName` thus using `$modelName::findMany($ids)` versus `Tonysm\GlobalId\Facades\Locator->locate()`'s `$modelName::find($id)`.

In the case of looking up Global IDs from a database, it's only necessary to query once per `$modelName` as shown here:

```
$gids = $users->merge($students)->sortBy('id')->map(fn ($model) => $model->toGlobalId());
# => [#,
#,
#,
#,
#,
#]

Tonysm\GlobalId\Facades\Locator::locateMany($gids);
# SELECT "users".* FROM "users" WHERE "users"."id" IN ($1, $2, $3)  [["id", 1], ["id", 2], ["id", 3]]
# SELECT "students".* FROM "students" WHERE "students"."id" IN ($1, $2, $3)  [["id", 1], ["id", 2], ["id", 3]]
# => [#, #, #, #, #, #]
```

Note the order is maintained in the returned results.

### Custom App Locator

[](#custom-app-locator)

A custom locator can be set for an app by calling `Tonysm\GlobalId\Locator::use()` and providing an app locator to use for that app. A custom app locator is useful when different apps collaborate and reference each others' Global IDs. When finding a Global ID's model, the locator to use is based on the app name provided in the Global ID url.

Using a custom Locator:

```
use Tonysm\GlobalId\GlobalId;
use Tonysm\GlobalId\Facades\Locator;
use Tonysm\GlobalId\Locators\LocatorContract;
use Illuminate\Support\Collection;

Locator::use('foo', new class implements LocatorContract {
    public function locate(GlobalId $globalId)
    {
        // ...
    }

    public function locateMany(Collection $globalIds, array $options = []): Collection
    {
        // ...
    }
});
```

After defining locators as above, URIs like `gid://foo/Person/1` will now use that locator. Other apps will still keep using the default locator.

### Custom Polymorphic Types

[](#custom-polymorphic-types)

When using the [Custom Polymorphic Types](https://laravel.com/docs/8.x/eloquent-relationships#custom-polymorphic-types) feature from Eloquent, the model name inside the GID URI will use your alias instead of the model's FQCN.

```
use App\Models\Person;

Relation::enforceMorphMap([
    'person' => Person::class,
]);

$gid = GlogalId::create(Person::create(['name' => 'a person']), [
    'app' => 'laravel',
]);

$gid->toString();
# => "gid://laravel/person/1"
```

Testing the Package
-------------------

[](#testing-the-package)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

You're encouraged to submit pull requests, propose features and discuss issues.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Drop me an email at [tonysm@hey.com](mailto:tonysm@hey.com?subject=Security%20Vulnerability) if you want to report security vulnerabilities.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Credits
-------

[](#credits)

- [Tony Messias](https://github.com/tonysm)
- [All Contributors](./CONTRIBUTORS.md)

###  Health Score

60

—

FairBetter than 99% of packages

Maintenance88

Actively maintained with recent releases

Popularity45

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 93% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~111 days

Recently: every ~291 days

Total

16

Last Release

56d ago

Major Versions

0.0.6 → 1.0.0-BETA2021-08-29

0.0.7 → 1.0.0-RC12021-09-07

PHP version history (3 changes)0.0.1PHP ^8.0

1.1.0PHP ^8.0|^8.1

1.3.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/a12e62d99ec6a83e48b2d79c7353417d82cecdca757a6766c5c32f22ceb6c55c?d=identicon)[tonysm](/maintainers/tonysm)

---

Top Contributors

[![tonysm](https://avatars.githubusercontent.com/u/1178621?v=4)](https://github.com/tonysm "tonysm (120 commits)")[![exonn-ozies](https://avatars.githubusercontent.com/u/146355503?v=4)](https://github.com/exonn-ozies "exonn-ozies (8 commits)")[![kanjibates](https://avatars.githubusercontent.com/u/949285?v=4)](https://github.com/kanjibates "kanjibates (1 commits)")

---

Tags

globalidhacktoberfestlaravellaraveltonysmglobalid-laravelglobalid

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/tonysm-globalid-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/tonysm-globalid-laravel/health.svg)](https://phpackages.com/packages/tonysm-globalid-laravel)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.8k28.9M627](/packages/spatie-laravel-data)[tonysm/importmap-laravel

Use ESM with importmap to manage modern JavaScript in Laravel without transpiling or bundling.

148399.8k1](/packages/tonysm-importmap-laravel)[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[hirethunk/verbs

An event sourcing package that feels nice.

513162.9k6](/packages/hirethunk-verbs)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

123544.7k](/packages/worksome-exchange)[ralphjsmit/livewire-urls

Get the previous and current url in Livewire.

82270.3k4](/packages/ralphjsmit-livewire-urls)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
