Some of laravel collection Methods in this Series. More in ... https://laravel.com/docs/10.x/collections
- Author: Divesh Kumar
- Twitter: @divesh20july
Setup Repo
git clone git@github.com:DiveshR/collection-methods-in-laravel.git
cd collection-methods-in-laravel
composer install
cp .env.example .env
php artisan key:generate
php artisan migrate --seed
php artisan cache:clear && php artisan config:clear
php artisan serve
Collections Methods Related to Numbers
It returns total number of records for a given model.
Article::count();
//In our case as realationship with user
Article::with('user')->count();
Article::where('is_pblished', true)->count();
It group the records by the given column and return count of each group.
NOTE: Column need to be numeric value otherwise it will be a type error exeption.
Acticle::pluck('user_id')->countBy();
It return the max value of a given columns.
Acticle::max('min_to_read'); //return article record having max value of min_to_value column
Article::whereBetween('user_id',[1,5])->max('min_to_read');//return article record having max value of min_to_value column from list of users id lies between 1 to 5
It return the min value of a given columns. Reverse of max
Acticle::min('min_to_read');
It retrive the middle value of a set of number.
Acticle::pluck('min_to_read')->median();
It return most frequent occuring value in a record.
Acticle::pluck('user_id')->mode(); //It output user with most articles.
Article::where('is_published',true)->pluck('user_id')->mode(); //It output user with most published articles.
It return random record from a given model.
Acticle::inRandomOrder()->first();
Article::inRandomOrder()->value('id') // it only return id randomly from records
It return total number of a given column.
Acticle::sum('min_to_read');
It filters the collection by a given key/value pair or a closure.
NOTE: Other than = operator you need to pass it as second agrument.
$collection = collect([
['name' => 'max', 'age' => 20],
['name' => 'william', 'age' => 29],
['name' => 'Tom', 'age' => 30],
['name' => 'Don Rickles', 'age' => 99],
['name' => 'John', 'age' => 50],
]);
$collection->where('age',90);
output
[
['name' => 'Don Rickles', 'age' => 99],
];
$collection->where('age','>',30);
output
[
['name' => 'Don Rickles', 'age' => 99],
['name' => 'John', 'age' => 50],
]
Article::where('is_published', true)->get();
Article::where('is_published',true)->where('min_to_read',5)->get();
// Can use callback function
Article::where(function($query) {
return $query->where('is_published',true);
})->get();
It uses strict comparison operator to compare two value.
$collection = collect([
['name' => 'max', 'age' => 20],
['name' => 'Max', 'age' => 29],
['name' => 'Tom', 'age' => 30],
['name' => 'Don Rickles', 'age' => 99],
['name' => 'John', 'age' => 50],
]);
return $collection->whereStrict('name','Max');
output
[
['name' => 'Max', 'age' => 29],
]