user2094178
user2094178

Reputation: 9454

Reusing object in the model

Currently I have a Ticket model.

I have these custom methods in this model:

public static function listing()
{
    $query = self::with('user', 'group', 'category', 'replies', 'club.country', 'club.membership.package', 'club.product');

    return $query->orderBy('updated_at', 'DESC')->paginate(20);
}

public static function total()
{
    return self::query()->count();
}

public static function open()
{
    return self::query()->where('status', '!=', 2)->count();
}

public static function search($search)
{
    $query = self::with('user', 'group', 'category', 'replies', 'club.country', 'club.membership.package', 'club.product');

    $query->where('subject', 'LIKE', '%'. $search .'%');

    return $query->orderBy('updated_at', 'DESC')->paginate(10);
}

When I use at the same time listing() or search() + total() and open() I believe it will be returned 3 objects.

So I wonder is it possible to inject/made availabe everywhere in the model the object returned by self::query()?

Now instead of calling/invoking self::query() or self::with() within all these custom methods I could instead refer to an existing object.

Upvotes: 0

Views: 138

Answers (1)

Marwelln
Marwelln

Reputation: 29413

What your asking for seems to be scopes.

<?php
class Model extends Eloquent {
    public function scopeTotal($query) {
        return $query->count();
    }

    public function scopeOpen($query) {
        return $query->where('status', 1);
    }
}

And then use it like Model::open()->get() to get all rows with status set to 1, or Model::open()->total() to count number of rows where status equals to 1 .

Upvotes: 1

Related Questions