Laravel Collections

Laravel Eloquent has Collections to return query results. They use methods which makes them powerful and helpful to use. You can modify, filter these methods which makes them very convenient. You can pass an array to the collection helper function to create a collection. Let’s see an example. You have a post model and finds all posts with php category.

$posts = App\Post::where('category', 'php')->get();

This command returns a collection. This collection is a Laravel class that uses arrays internally and adds many features to them by using collect method as given below.

$collection = collect([

    [

        'user_id'=> '1',

        'title'=> 'Helpers in Laravel',

        'content'=> 'Create custom helpers in Laravel',

        'category'=> 'php'

    ],

    [

        'user_id'=> '2',

        'title'=> 'Testing in Laravel',

        'content'=> 'Testing File Uploads in Laravel',

        'category'=> 'php'

    ],

    [

        'user_id'=> '3',

        'title'=> 'Telegram Bot',

        'content'=> 'Crypto Telegram Bot in Laravel',

        'category'=> 'php'

    ],

]);

There are helper methods. To use them first we need to query the database get all result we need. Then use collection methods to filter and modify them. We have filter(), search(), chunk(), dump(), map(), zip(), whereNotin(), max(), pluck(), each(), tap(), pipe(), contains(), forget(), avg() methods.