laravel

Laravel Collection Tutorial

Laravel collection is a useful feature of the Laravel framework. A collection works like a PHP array, but it is more convenient. The collection class is located in the Illuminate\Support\Collection location. A collection allows you to create a chain of methods to map or reduce arrays. It is not changeable, and a new collection returns when the collection method is called. It is an API wrapper for PHP array functions and a collection can be generated from an array. This tutorial shows you how to create and use a collection in any Laravel project.

Prerequisite

You must create a Laravel project before starting this tutorial. You must also have a basic knowledge of controller and routing.

Create a Collection

Create the controller named CollectionController and write the necessary code to create a new collection inside the controller. Run the following command to create the controller.

$ php artisan make:controller CollectionController

You can create a collection using a collection class or the collect() method. Both ways are shown below. Add the following line at the top of the CollectionController class to use the collection class.

//Add the collection class
use Illuminate\Support\Collection;

A. Create Collection Using Class

Create the collection_class() method with the following code inside the CollectionConntroller. Here, a collection of numbers is created with a collection class. When this method is called, the values of the collection variable will be shown in the browser.

public function collection_class(){

    //Create a new collection using Collection class
    $collection1 = new Collection([67,34,89,56,23]);

    //dump the variable content in the browser
    dd($collection1);
}

Add the following route in the routes\web.php file to call the collection_class().

Route::get('collect1', 'CollectionController@collection_class');

Enter the following URL in the browser to check the output.

http://localhost:8000/collect1

The following output will appear after running the URL. The five numbers of the collection are printed here.

B. Create Collection Using Method

A collection can also be created using the collect() method. Add the following collect_method() inside the CollectionController to create a collection of strings using the collect() method. When this method is called, the values of the collection variable will be shown in the browser, as before.

public function collect_method(){

    //Create a new collection using the collect method
    $collection2 = collect(["Good", "Better", "Best"]);

    //dump the variable content in the browser
    dd($collection2);

}

Add the following route in the routes\web.php file to call the collect_method().

Route::get('collect2', 'CollectionController@collect_method');

Enter the following URL in the browser to check the output.

http://localhost:8000/collect2

The following output will appear after running the URL. The three string values of the collection are printed here.

Search Data in Collection

The data can be searched from the collection in multiple ways. Add the following code inside the CollectionController. Two types of searching are shown in the code. First, a collection of customers is defined, and the contains() method is used to search the customer named ‘Janifer.’ Next, a collection of the multi-dimensional array is defined, and the where() method is used for two types of searching in the collection. The first where() method is used to search the information, where the ID key contains the value ‘011176645.’ The second where() method is used to search for the information where the marks of CSE409 is 88.

public function search_data()
{
    //Declare a collection
    $customer = collect([['id' => '894673', 'name' => 'Rahman', 'email' =>  'rah@gmail.com'],
    ['id' => '454886', 'name' => 'Janifer', 'email' => 'ganifer@gmail.com'],
    ['id' => '306007', 'name' => 'Micheal', 'email' => 'mic@gmail.com']]);
   
    //Search using contains method
    if ($customer->contains('name', 'Janifer'))
    {
        echo "Janifer exists in the customer list.<br/>";
    }
   
    //Declare another collection
    $marks = collect([
    ['ID' => '011176644', 'marks' => ['CSE401' => 87, 'CSE409' => 88]],
    ['ID' => '011176645', 'marks' => ['CSE402' => 69, 'CSE409' => 75]],
    ]);

    //Search using where method
    echo $marks->where('ID', '011176645')."<br/>";
    echo $marks->where('marks.CSE409', 88);
}

Add the following route in the routes\web.php file to call the search_data().

Route::get('src_collection', 'CollectionController@search_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/src_collection

The following output will appear after running the URL.

Filter Collection Data

The filter() method is used to filter data from the collection. Add the following code in CollectionController. A collection of products is defined in the code that contains product name and price. The filter() method is used to filter data from the collection of which the price value is greater than 4000. The collection of filtered data is converted into an array and printed by the for loop.

public function filter_data()
{
    //Declare a collection
    $products = collect([
        ['product' => 'HDD', 'price' => 6000],
        ['product' => 'Mouse', 'price' => 500],
        ['product' => 'Monitor', 'price' => 5000],
        ['product' => 'Printer', 'price' => 4000],
    ]);

    //Create another list after filtering the data based on price value
    $filter_price = $products->filter(function ($item) {
        return data_get($item, 'price') > 4000;
    });

    //Read all data as array  from the new collection
    $filtered = $filter_price->all();

    //Iterating the array values using loop
    foreach($filtered as $value)
    {
        echo "Name: ".$value['product'].", "."Price: ".$value['price']."<br/>";
    }
}

Add the following route in the routes\web.php file to call the filter_data().

Route::get('filter_collection', 'CollectionController@filter_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/filter_collection

The following output will appear after running the URL.

Sort Collection Data

Various sort methods exist in Laravel to sort collection data. Add the following code in the CollectionController. A collection of books is defined in the code. The sortBy() method is used to sort the collection data based on the key ‘author.’ Then, the values of the sorted collection variable are printed in the browser.

public function sort_data(){

    //Declare a collection
    $books = collect([
    ['name' => 'Python Cookbook: Recipes for Mastering Python 3',
     'author' => 'David Beazley'],
    ['name' => 'Learn Python in 1 Day: Complete Python Guide with Examples',
    'author' => 'Krishna Rungta'],
    ['name' => 'Python Programming: An Introduction to Computer Science',
    'author' => 'John M. Zelle'],
    ['name' => 'Python Pocket Reference 5ed: Python in Your Pocket',
    'author' => 'Mark Lutz']
    ]);

    //Sort the collection data based on author name
    $sortedBook = $books->sortBy('author');

    //dump the variable content in the browser
    dd($sortedBook->values()->toArray());
}

Add the following route in the routes\web.php file to call the sort_data().

Route::get('sort_collection', 'CollectionController@sort_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/sort_collection

The following output will appear after running the URL.

Slice Collection Data

A particular portion can be cut from the collection using the take() method. Add the following code in the CollectionController. The take() method is used in the code to create a new list by cutting the first three items from the collection. Next, the for loop prints the values of the new collection.

public function slice_data(){

    //Declare a collection
    $languages = collect(['PHP', 'Bash', 'Python', 'Java', 'C#', 'C++']);

    //Retrive the first three data
    $slice = $languages->take(3);
   
    //Iterating collection values
    foreach($slice as $value)
    {
        echo $value." ";
    }
}

Add the following route in the routes\web.php file to call the slice_data().

Route::get('slice_collection', 'CollectionController@slice_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/slice_collection

The following output will appear after running the URL.

Find the Difference Between Two Collections

The diff() method is used to find values from the first collection that do not exist in the second collection. Add the following code in CollectionController. Two collection variables are defined here. The diff() method generates a new collection after retrieving the values from list1 that do not exist in list2.

public function find_diff(){

    //Declare two collection
    $list1 = collect(['Notebook', 'Pen', 'Sharpner', 'Scale', 'Pencil']);
    $list2 = collect(['Pencil', 'Color Pencil', 'Color Paper','Pen']);

    //Find which data exists in list1 but not in list2
    $newList = $list1->diff($list2);

    //dump the variable content in the browser
    dd($newList);
}

Add the following route in the routes\web.php file to call the find_diff().

Route::get('diff_collection', 'CollectionController@find_diff');

Enter the following URL in the browser to check the output.

http://localhost:8000/diff_collection

The following output will appear after running the URL.

Flip Collection Data

The flip() method is used to make the key to the value and the value to the key of the collection. Add the following code in the CollectionController to check the function of the flip() method. A collection of three items is defined in the code. The flip() method is applied to the collection and the output of the flip() method is printed by using the dd() method.

public function flip_data(){

    //Declare the collection
    $products = collect(['name' => 'Samsung A40','brand' => 'Samsung','price' => '$300']);
    //dump the variable content in the browser
    dd($products->flip());
}

Add the following route in the routes\web.php file to call the flip_data().

Route::get('flip_collection', 'CollectionController@flip_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/flip_collection

The following output will appear after running the URL.

Retrieve the Collection

The get() method is used to read the value of a particular key from the collection. Add the following code in the CollectionController. The value of the ‘name’ key is retrieved in the code by using the get() method.

Public function retrieve_data(){

    //Declare the collection
    $products = collect(['name' => 'Samsung A40','brand' => 'Samsung','price' => '$300']);
    dd($products->get('name'));
}

Add the following route in the routes\web.php file to call the retrieve_data().

Route::get('read_collection', 'CollectionController@retrieve_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/read_collection

The following output will appear after running the URL.

Group Collection Data

The groupBy() method is used to create a new collection from another collection by grouping based on the particular key value. Add the following code inside the CollectionController. The groupBy() method is used here to return a new collection by grouping the values based on the ‘Apr’ key.

public function group_data(){

public function group_data(){
    $sales = collect([
        ['Jan' => 100000],
        ['Mar' => 500000],
        ['Apr' => 600000],
        ['Jan' => 450000],
        ['Jun' => 230000],
        ['Aug' => 600000],
        ['Sep' => 789333],
        ['Jul' => 452000],
        ['Jan' => 700000],
        ['Apr' => 490000],
        ['Jun' => 670000],
        ['Apr' => 560000]
    ]);
    dd($sales->groupBy('Apr'));
}

Add the following route in the routes\web.php file to call the group_data().

Route::get('group_collection', 'CollectionController@group_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/group_collection

The following output will appear after running the URL.

Combine Collection Data

The implode() method is used to combine particular key values from the collection. Add the following code inside the CollectionController. The implode() method is used here to combine the values of the name key of the collection with space.

public function join_data(){
    //Declare a collection
    $customer = collect([['id' => '894673', 'name' => 'Rahman', 'email' =>  'rah@gmail.com'],
    ['id' => '454886', 'name' => 'Janifer', 'email' => 'ganifer@gmail.com'],
    ['id' => '306007', 'name' => 'Micheal', 'email' => 'mic@gmail.com']]);
   
    //Combine and print the value
    dd($customer->implode('name', ' '));
}

Add the following route in the routes\web.php file to call the join_data().

Route::get('join_collection', 'CollectionController@join_data');

Enter the following URL in the browser to check the output.

http://localhost:8000/join_collection

The following output will appear after running the URL.

Read Collection Keys

The keys() method is used to create a new collection with all the keys of another collection. Add the following code inside the CollectionController. The collection defined in the code contains different types of data as items, such as the value with numeric index, the value with key, and another array.

public function read_keys(){
    //Declare a collection
    $mixdata = collect([
        ['website' => 'google.com', 'type' => 'search engine'],'language' => 'PHP',
    1234, 'name' => 'Fahmida','game' => 'PUBG','color' =>'blue']);

    //Print the new collection generated by keys() method
    dd($mixdata->keys());

}

Add the following route in the routes\web.php file to call the read_keys().

Route::get('key_collection', 'CollectionController@read_keys');

Enter the following URL in the browser to check the output.

http://localhost:8000/key_collection

The following output will appear after running the URL.

Conclusion

Laravel collection allows you to do many different types of tasks with data, like PHP arrays. Some useful methods of Laravel Collection are explained in this tutorial by using very simple code. Eloquent ORM is another use of the collection in Laravel that is not covered in this tutorial. One major limitation of the collection class is that it generates a new collection every time a method is called because it is not mutable. After reading this tutorial, the reader should now know some basic uses of Laravel collection.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.