• Stars
    star
    102
  • Rank 335,584 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

Laravel Eloquent Scope as Select

Latest Version on Packagist run-tests Quality Score Total Downloads Buy us a tree

Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

πŸ“Ί Want to see this package in action? Join the live stream on December 3 at 14:00 CET: https://youtu.be/0vR8IQSFsfQ

Requirements

  • PHP 8.1+
  • Laravel 10.0

This package is tested with GitHub Actions using MySQL 8.0, PostgreSQL 10.8 and SQLite.

Features

  • Add a subquery based on a query scope.
  • Add a subquery using a Closure.
  • Shortcuts for calling scopes by using a string or array.
  • Support for more than one subquery.
  • Support for flipping the result.
  • Zero third-party dependencies.

Related package: Laravel Eloquent Where Not

Sponsor this package!

❀️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please consider sponsoring the maintenance and development. Keeping track of issues and pull requests takes time, but we're happy to help!

Laravel Splade

Did you hear about Laravel Splade? 🀩

It's the magic of Inertia.js with the simplicity of Blade. Splade provides a super easy way to build Single Page Applications using Blade templates. Besides that magic SPA-feeling, it comes with more than ten components to sparkle your app and make it interactive, all without ever leaving Blade.

Blogpost

If you want to know more about the background of this package, please read the blogpost: Stop duplicating your Eloquent query scopes and constraints. Re-use them as select statements with a new Laravel package.

Installation

You can install the package via composer:

composer require protonemedia/laravel-eloquent-scope-as-select

Add the macro to the query builder, for example, in your AppServiceProvider. By default, the name of the macro is addScopeAsSelect, but you can customize it with the first parameter of the addMacro method.

use ProtoneMedia\LaravelEloquentScopeAsSelect\ScopeAsSelect;

public function boot()
{
    ScopeAsSelect::addMacro();

    // or use a custom method name:
    ScopeAsSelect::addMacro('withScopeAsSubQuery');
}

Short API description

For a more practical explanation, check out the usage section below.

Add a select using a Closure. Each Post model, published or not, will have an is_published attribute.

Post::addScopeAsSelect('is_published', function ($query) {
    $query->published();
})->get();

The example above can be shortened by using a string, where the second argument is the name of the scope:

Post::addScopeAsSelect('is_published', 'published')->get();

You can use an array to call multiple scopes:

Post::addScopeAsSelect('is_popular_and_published', ['popular', 'published'])->get();

Use an associative array to call dynamic scopes:

Post::addScopeAsSelect('is_announcement', ['ofType' => 'announcement'])->get();

If your dynamic scopes require multiple arguments, you can use an associative array:

Post::addScopeAsSelect('is_announcement', ['publishedBetween' => [2010, 2020]])->get();

You can also mix dynamic and non-dynmaic scopes:

Post::addScopeAsSelect('is_published_announcement', [
    'published',
    'ofType' => 'announcement'
])->get();

The method has an optional third argument that flips the result.

Post::addScopeAsSelect('is_not_announcement', ['ofType' => 'announcement'], false)->get();

Usage

Imagine you have a Post Eloquent model with a query scope.

class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at');
    }
}

Now you can fetch all published posts by calling the scope method on the query:

$allPublishedPosts = Post::published()->get();

But what if you want to fetch all posts and then check if the post is published? This scope is quite simple, so you can easily mimic the scope's outcome by checking the published_at attribute:

Post::get()->each(function (Post $post) {
    $isPublished = !is_null($post->published_at);
});

This is harder to achieve when scopes get more complicated or when you chain various scopes. Let's add a relationship and another scope to the Post model:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at');
    }

    public function scopePublishedInCurrentYear($query)
    {
        return $query->whereYear('published_at', date('Y'));
    }
}

Using Eloquent, we can fetch all posts from this year with at least ten comments.

$recentPopularPosts = Post::query()
    ->publishedInCurrentYear()
    ->has('comments', '>=', 10)
    ->get();

Great! Now we want to fetch all posts again, and then check if the post was published this year and has at least ten comments.

Post::get()->each(function (Post $post) {
    $isRecentAndPopular = $post->comments()->count() >= 10
        && optional($post->published_at)->isCurrentYear();
});

Well, you get the idea. This is bound to get messy and you're duplicating logic as well.

Solution

Using the power of this package, you can re-use your scopes when fetching data. The first example (published scope) can be narrowed down to:

$posts = Post::addScopeAsSelect('is_published', function ($query) {
    $query->published();
})->get();

With short closures, a feature which was introduced in PHP 7.4, this can be even shorter:

$posts = Post::addScopeAsSelect('is_published', fn ($query) => $query->published())->get();

Now every Post model will have an is_published boolean attribute.

$posts->each(function (Post $post) {
    $isPublished = $post->is_published;
});

You can add multiple selects as well, for example, to combine both scenarios:

Post::query()
    ->addScopeAsSelect('is_published', function ($query) {
        $query->published();
    })
    ->addScopeAsSelect('is_recent_and_popular', function ($query) {
        $query->publishedInCurrentYear()->has('comments', '>=', 10);
    })
    ->get()
    ->each(function (Post $post) {
        $isPublished = $post->is_published;

        $isRecentAndPopular = $post->is_recent_and_popular;
    });

Shortcuts

Instead of using a Closure, there are some shortcuts you could use (see also: Short API description):

Using a string instead of a Closure:

Post::addScopeAsSelect('is_published', function ($query) {
    $query->published();
});

// is the same as:

Post::addScopeAsSelect('is_published', 'published');

Using an array instead of Closure, to support multiple scopes and dynamic scopes:

Post::addScopeAsSelect('is_announcement', function ($query) {
    $query->ofType('announcement');
});

// is the same as:

Post::addScopeAsSelect('is_announcement', ['ofType' => 'announcement']);

You can also flip the result with the optional third parameter (it defaults to true):

$postA = Post::addScopeAsSelect('is_announcement', ['ofType' => 'announcement'])->first();
$postB = Post::addScopeAsSelect('is_not_announcement', ['ofType' => 'announcement'], false)->first();

$this->assertTrue($postA->is_announcement)
$this->assertFalse($postB->is_not_announcement);

Testing

composer test

Changelog

Please see CHANGELOG for more information about what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Other Laravel packages

  • Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel Form Components: Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel WebDAV: WebDAV driver for Laravel's Filesystem.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Treeware

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

More Repositories

1

laravel-ffmpeg

This package provides an integration with FFmpeg for Laravel. Laravel's Filesystem handles the storage of the files.
PHP
1,511
star
2

laravel-splade

πŸ’« The magic of Inertia.js with the simplicity of Blade πŸ’« - Splade provides a super easy way to build Single Page Applications (SPA) using standard Laravel Blade templates, and sparkle it to make it interactive. All without ever leaving Blade.
PHP
1,382
star
3

laravel-cross-eloquent-search

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.
PHP
990
star
4

laravel-form-components

A set of Blade components to rapidly build forms with Tailwind CSS (v1.0 and v2.0) and Bootstrap 4/5. Supports validation, model binding, default values, translations, Laravel Livewire, includes default vendor styling and fully customizable!
PHP
807
star
5

inertiajs-tables-laravel-query-builder

Inertia.js Tables for Laravel Query Builder
PHP
425
star
6

eddy-server-management

Open-Source Solution for Server Provisioning and Zero-Downtime PHP Deployment
PHP
423
star
7

laravel-verify-new-email

This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
PHP
384
star
8

laravel-analytics-event-tracking

Laravel package to easily send events to Google Analytics
PHP
243
star
9

laravel-paddle

Paddle.com API integration for Laravel with support for webhooks/events
PHP
195
star
10

laravel-mixins

A collection of Laravel goodies.
PHP
135
star
11

laravel-task-runner

A package to write Shell scripts like Blade Components and run them locally or on a remote server
PHP
116
star
12

laravel-single-session

This package prevents a User from being logged in more than once. It destroys the previous session when a User logs in and thereby allowing only one session per user.
PHP
101
star
13

laravel-xss-protection

Laravel XSS Protection Middleware
PHP
99
star
14

laravel-guidelines

Not necessarily coding standards (naming conventions, avoid else, etc.), but more like 'app'-guidelines - things you don't want to forget.
PHP
91
star
15

laravel-api-health

Monitor first and third-party services and get notified when something goes wrong!
PHP
87
star
16

form-components-pro

A set of Vue 3 components to rapidly build forms with Tailwind CSS 3. It supports validation, model binding, integrates with Autosize/Choices.js/Flatpickr, includes default vendor styling and is fully customizable! Even better in conjunction with Laravel Jetstream + Inertia.js.
JavaScript
82
star
17

laravel-webdav

WebDAV Serivce Provider for Laravel
PHP
59
star
18

laravel-blade-on-demand

Compile Blade templates in memory
PHP
50
star
19

inertia-vue-modal-poc

Proof of Concept: Load any route into a modal with Inertia.js
Vue
49
star
20

laravel-splade-core

A package to use Vue 3's Composition API in Laravel Blade components.
PHP
42
star
21

laravel-eloquent-where-not

This Laravel package allows you to flip/invert an Eloquent scope, or really any query constraint.
PHP
27
star
22

laravel-content

You provide the WYSIWYG editor, Media uploader, etc., and the package handles the validation, multi-language, storage, caching, sanitizing, etc.
PHP
23
star
23

inertiajs-events-laravel-dusk

Inertia.js Events for Laravel Dusk
PHP
22
star
24

laravel-dusk-fakes

Persistent Fakes for Laravel Dusk
PHP
17
star
25

laravel-minio-testing-tools

This package provides a trait to run your tests against a MinIO S3 server.
PHP
11
star
26

splade.dev

Source code for https://splade.dev
PHP
8
star
27

laravel-splade-docs

7
star
28

laravel-viewi

[WIP] Viewi for Laravel proof-of-concept: Build full-stack and completely reactive user interfaces with PHP.
PHP
5
star
29

eddy-backup-cli

Backup CLI for Eddy Server Management
PHP
3
star
30

form-components-pro-docs

A set of Vue components to rapidly build forms with Tailwind CSS v2.0. It supports validation, model binding, includes default vendor styling and is fully customizable!
JavaScript
3
star
31

laravel-tracer

[WIP] Trace authenticated users
PHP
2
star
32

eddy-filesystem-cli

PHP
1
star
33

laravel-ffmpeg-demo-app

A demo app to show all the cool things you can do with Laravel FFmpeg
1
star
34

php-apple-mapkit-token

Create a MapKit JS Token with PHP
1
star
35

laravel-browser-kit-macro

A macro to use the Laravel 5.3 testing layer inside your Laravel >5.3 tests
PHP
1
star
36

laravel-splade-plugin-skeleton

PHP
1
star