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.
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.
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.
//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().
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.
//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().
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.
{
//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().
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.
{
//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().
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.
//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().
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.
//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().
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.
//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().
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.
//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().
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.
//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().
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(){
$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().
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.
//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().
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.
//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().
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.
from Linux Hint https://ift.tt/3kZaKwx
0 Comments