Make your accessors smarter

Overview

Computed properties for Eloquent

Code quality Latest Version on Packagist Licence Build Status

Laravel 5.4+

Based on this tweet: https://twitter.com/reinink/status/899713609722449920

Some examples for better understanding of this power:

class Order extends Model
{
    use ComputedProperties;

    public function products()
    {
        return $this->hasMany(OrderProduct::class);
    }

    public function computedSum($order)
    {
        return OrderProduct::select(new Expression('sum(price * count)'))
            ->where('order_id', $order->id);
    }
}

Now, we can get order sum with $order->sum. Yep, we can get this functionality with getSumAttribute but wait! The real power of this package is that we can use this method inside our queries:

$orders = Order::withComputed('sum')->get()

We eager loaded sum attribute without N+1 problem.

But there is more! You can add having or orderBy clauses to such queries for filtering and sorting!

Order::withComputed('sum')->orderBy('sum', 'desc')->get()

Installation

You can install the package via composer:

composer require n7olkachev/laravel-computed-properties

Next, add ComputedProperties trait to your models:

use ComputedProperties;

That's all!

More examples

class Page extends Model
{
    use ComputedProperties;

    public $timestamps = false;

    protected $casts = [
        'last_view' => 'datetime',
        'first_view' => 'datetime',
    ];

    public function computedLastView($page)
    {
        return PageView::select(new Expression('max(viewed_at)'))
            ->where('page_id', $page->id);
    }

    public function computedFirstView($page)
    {
        return PageView::select(new Expression('min(viewed_at)'))
            ->where('page_id', $page->id);
    }
}

We can find Page by its first view:

$page = Page::withComputed('first_view')
    ->having('first_view', Carbon::create(2017, 8, 16, 0, 0, 0))
    ->first();

Or by both first_view and last_view

$page = Page::withComputed(['first_view', 'last_view'])
    ->having('first_view', Carbon::create(2017, 8, 16, 0, 0, 0))
    ->having('last_view', Carbon::create(2017, 8, 21, 0, 0, 0))
    ->first();

We can order pages by theirs last_view

$pages = Page::withComputed('last_view')
    ->orderBy('last_view', 'desc')
    ->get()

Testing

$ composer test

Credits

Sponsored by

https://websecret.by/

Web agency based in Minsk, Belarus

License

The MIT License (MIT)

Comments
  • Add Laravel 5.7 support

    Add Laravel 5.7 support

    Hi,

    I want to use this awesome package in my Laravel 5.7 project. I don't see any issues while using this package with Laravel 5.7.

    Please tag a new version ASAP.

    Thanks.

    opened by ankurk91 2
  • Benefit of this package vs simple cacher

    Benefit of this package vs simple cacher

    How is this package any better than just doing something like the below:

    public function getSumAttribute()
    {    
        return $this->rememberAs('sum', function() {
            OrderProduct::select(new Expression('sum(price * count)'))
                ->where('order_id', $this->id);
        });
    }
    

    If you have a basic implementation of rememberAs on your model which sees if the key already exists and if not, run the closure and set the value on the model.

    opened by garygreen 2
  • This isn't 'real' computed properites

    This isn't 'real' computed properites

    I assume the computed name has come from the world of Vue.

    Computed properties in Vue react to data that changes on the model, so if you were to update anything in which the computed property used, it will re-compute the computed property.

    This is more of a 'watch out' type warning to people thinking it's 'real' computed properties (as they know it) from Vue.

    opened by garygreen 2
  • Loose package weight by excluding some files

    Loose package weight by excluding some files

    Hi,

    Lets not publish all those file. .gitattributes can be used to exclude files from final archive that is downloaded by composer.

    Read more

    • https://madewithlove.be/gitattributes/
    • https://alexbilbie.com/2012/11/exclude-objects-with-gitattributes/
    • http://www.pixelite.co.nz/article/using-git-attributes-exclude-files-your-release/
    opened by ankurk91 1
  • Laravel 5.6 still not working

    Laravel 5.6 still not working

    composer require n7olkachev/laravel-computed-properties

    Using version ^1.1 for n7olkachev/laravel-computed-properties ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

    Problem 1 - Conclusion: remove laravel/framework v5.6.26 - Conclusion: don't install laravel/framework v5.6.26 - n7olkachev/laravel-computed-properties v1.1.0 requires illuminate/config ~5.4.0 -> satisfiable by illuminate/config[v5.4.0, v5.4.13, v5.4.17, v5.4.19, v5.4.27, v5.4.36, v5.4.9]. - n7olkachev/laravel-computed-properties v1.1.1 requires illuminate/config ~5.4.0|~5.5.0 -> satisfiable by illuminate/config[v5.4.0, v5.4.13, v5.4.17, v5.4.19, v5.4.27, v5.4.36, v5.4.9, v5.5.0, v5.5.16, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v 5.5.36, v5.5.37, v5.5.39, v5.5.40]. - don't install illuminate/config v5.4.0|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.13|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.17|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.19|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.27|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.36|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.4.9|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.0|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.16|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.17|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.2|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.28|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.33|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.34|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.35|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.36|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.37|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.39|don't install laravel/framework v5.6.26 - don't install illuminate/config v5.5.40|don't install laravel/framework v5.6.26 - Installation request for laravel/framework (locked at v5.6.26, required as 5.6.*) -> satisfiable by laravel/framework[v5.6.26]. - Installation request for n7olkachev/laravel-computed-properties ^1.1 -> satisfiable by n7olkachev/laravel-computed-properties[v1.1.0, v1.1.1].

    Installation failed, reverting ./composer.json to its original content.

    opened by Develop-FM 1
  • Add to Laravel core

    Add to Laravel core

    https://twitter.com/davidgolsen/status/920941756681719809

    I wholeheartedly agree as it fits right in and should be a standard feature :) Perhaps create a laravel/internals issue or submit a PR in the hopes it gets accepted faster?

    opened by sebastiaanluca 1
Releases(v1.1.3)
Owner
Nikita Tolkachev
Nikita Tolkachev
Make your Laravel app comply with the crazy EU cookie law

Make your Laravel app comply with the crazy EU cookie law All sites owned by EU citizens or targeted towards EU citizens must comply with a crazy EU l

Spatie 1.2k Jan 4, 2023
A package to easily make use of Iconic icons in your Laravel Blade views.

Blade Iconic A package to easily make use of Iconic icons in your Laravel Blade views. For a full list of available icons see the SVG directory. Iconi

Malik Alleyne-Jones 17 Aug 25, 2022
A package to easily make use of Simple Icons in your Laravel Blade views.

Blade Simple Icons A package to easily make use of Simple Icons in your Laravel Blade views. For a full list of available icons see the SVG directory.

UB Labs 12 Jan 17, 2022
Make your Laravel app comply with the refuse/accept cookie law

Make your Laravel app comply with the refuse/accept cookie law All sites owned by EU citizens or targeted towards EU citizens must comply with a crazy

RETINENS - Multimedia solutions 37 Mar 22, 2022
A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

Andrew Huggins 94 Nov 22, 2022
A package to easily make use of SVG icons in your Laravel Blade views.

Blade Icons A package to easily make use of SVG icons in your Laravel Blade views. Originally "Blade SVG" by Adam Wathan. Turn... <!-- camera.svg -->

Blade UI Kit 1.7k Jan 2, 2023
Make your own custom cast type for Laravel model attributes

Laravel Custom Casts Make your own cast type for Laravel model attributes Laravel custom casts works similarly to Eloquent attribute casting, but with

Vladimir Ković 220 Oct 28, 2022
Make requests to the Shopify API from your Laravel app

Make requests to the Shopify API from your Laravel app The signifly/laravel-shopify package allows you to easily make requests to the Shopify API. Ins

Signifly 147 Dec 30, 2022
Make your church sermons available for download. For the latest version, go:

Laravel Church Sermons App Laravel church sermons app is basically an app for churches to make available the messages preached in church for all membe

Dammy 28 Nov 13, 2022
Relational Metrics - lararvel package help you to make your metrics easier

Relational Metrics This package will help you to make your metrics easier, You could get metrics about your Models, Models depending on their relation

Syrian Open Source 25 Oct 12, 2022
A package to easily make use of Iconsax in your Laravel Blade views.

Blade Iconsax A package to easily make use of Iconsax in your Laravel Blade views. This package contains 1.000 icons in 6 diferent styles, a total of

Guilherme Saade 4 Oct 22, 2022
A simple `make:view` command for Laravel applications.

A simple make:view command for Laravel applications. Quickly generate a new Blade view from the console using artisan make:view. Installation You can

Ryan Chandler 10 Oct 17, 2022
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022
This package gives you a set of conventions to make the most out of Hotwire in Laravel

Introduction This package gives you a set of conventions to make the most out of Hotwire in Laravel (inspired by the turbo-rails gem). There is a comp

Tony Messias 665 Jan 2, 2023
Make any class queue aware in a Laravel app

Make any class queue aware This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. Support us We in

Spatie 8 Jun 17, 2022
Extend Laravel PHP framework to make working with Aiven databases simpler

Aiven Commands for Laravel ✨ Add some Aiven magic to your Laravel project ✨ This Laravel package provides some aiven commands for artisan to help with

Aiven 8 Aug 19, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023
This package provides you with a simplistic `php artisan make:user` command

Laracademy Generators Laracademy make:user Command - provides you with a simplistic artisan command to generate users from the console. Author(s): Lar

Laracademy 18 Jan 19, 2019
Interactive Make Command for Laravel

Interactive Make for Laravel 5.4 Getting Started To get started you need to install the package with Composer: composer require laracademy/interactive

Laracademy 352 Dec 16, 2022