Ashkru
Ashkru

Reputation: 1635

Laravel - Put all records together?

I want to get every 'stat' value from every record in where government_type = 'higher_government' but at the moment my code only gets the stats instances for the first government role it finds, how can I put together all of the stats in some sort of array?

$higherGovernment = Cache::remember('government.higher_government', 1, function() {
    return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});

Stats relationship:

public function government_role()
    {
        return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
    }

Government relationship:1

    public function stats(){
       return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
   }

Upvotes: 2

Views: 72

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Use pluck()->toArray()

GovernmentRole::where('government_type', 'higher_government')->pluck('stats')->toArray();

This code will return an array of stats properties.

Upvotes: 1

benJ
benJ

Reputation: 2590

You should be able to use the pluck() method from Eloquent's Collection. https://laravel.com/docs/5.3/collections#method-pluck

Change your query to something like:

GovernmentRole::where('government_type', 'higher_government')
    ->get()
    ->pluck('stats', 'government_id');

This will give you a collection containing government_id => stats.

If you want an array rather than a collection, simply add ->toArray()

Upvotes: 0

Related Questions