Laravel Collection And Laravel Forge Tutorial

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Learn about Laravel Collection and its methods with examples. This tutorial also explains Laravel Forge with advantages and pricing:

In the Laravel Session tutorial of the Laravel Tutorial series, we learned about file upload, download, file permission, Laravel authentication & authorization, sending emails, etc. with examples.

In this tutorial, we have discussed how to create a Laravel collections and the methods with examples. We will also learn to set up a project for Laravel collection, collection example, advantages of Laravel forge, it’s pricing plans, etc.

For all the examples, we have used Laravel version 7.

Laravel Collections and Laravel Forge Tutorial

Prerequisites

In our previous tutorials, we have covered basic concepts of Laravel version 7, and you need to be familiar with those topics for a better understanding of this tutorial.

Let’s begin!

Laravel Collections

Laravel collection is a convenient wrapper to work with array data. Laravel uses the Illuminate\Support\Collection class to work with collections. The eloquent queries return outputs as collection instances.

How To Create Laravel Collection

Creating a Laravel collection is easy. You can create a collection as shown below:

$collection = collect([1, 2, 3]);

Laravel Collection Methods

The following list shows the full set of methods available in the collection class. In this tutorial, we have only discussed 15 of them in detail.

>> Refer to the official documentation of Laravel collections to know more about other available methods.

  • all
  • average
  • avg
  • chunk
  • collapse
  • collect
  • combine
  • concat
  • contains
  • containsStrict
  • count
  • countBy
  • crossJoin
  • dd
  • diff
  • diffAssoc
  • diffKeys
  • dump
  • duplicates
  • duplicatesStrict
  • each
  • eachSpread
  • every
  • except
  • filter
  • first
  • firstWhere
  • flatMap
  • flatten
  • flip
  • forget
  • forPage
  • get
  • groupBy
  • has
  • implode
  • intersect
  • intersectByKeys
  • isEmpty
  • isNotEmpty
  • join
  • keyBy
  • keys
  • last
  • macro
  • make
  • map
  • mapInto
  • mapSpread
  • mapToGroups
  • mapWithKeys
  • max
  • median
  • merge
  • mergeRecursive
  • min
  • mode
  • nth
  • only
  • pad
  • partition
  • pipe
  • pluck
  • pop
  • prepend
  • pull
  • push
  • put
  • random
  • reduce
  • reject
  • replace
  • replaceRecursive
  • reverse
  • search
  • shift
  • shuffle
  • skip
  • skipUntil
  • skipWhile
  • slice
  • some
  • sort
  • sortBy
  • sortByDesc
  • sortDesc
  • sortKeys
  • sortKeysDesc
  • splice
  • split
  • sum
  • take
  • takeUntil
  • takeWhile
  • tap
  • times
  • toArray
  • toJson
  • transform
  • union
  • unique
  • uniqueStrict
  • unless
  • unlessEmpty
  • unlessNotEmpty
  • unwrap
  • values
  • when
  • whenEmpty
  • whenNotEmpty
  • where
  • whereStrict
  • whereBetween
  • whereIn
  • whereInStrict
  • whereInstanceOf
  • whereNotBetween
  • whereNotIn
  • whereNotInStrict
  • whereNotNull
  • whereNull
  • wrap
  • zip

Let’s discuss 15 common methods below:

#1) first()

Description: This method returns the first element in the collection.

Example 1:

collect([1, 2, 3, 4, 5])->first();

// The output is 1.

Example 2:

collect([1, 2, 3, 4, 5])->first(function ($value, $key) {
    return $value > 3;
});

// The output is 4.

Note: If the collection is empty, the return value will be null.

#2) last()

Description: This method returns the last element in the collection.

Example 1:

collect([1, 2, 3, 4, 5])->last();

// The output is 5.

Example 2:

collect([1, 2, 3, 4, 5])->last(function ($value, $key) {
     return $value < 3;
});

// The output is 2.

Note: If the collection is empty, the return value will be null.

#3) max()

Description: This method returns the maximum value in the collection.

Example 1:

collect([1, 2, 3, 4, 5])->max();

// The output is 5.

Example 2:

$max = collect([['foo' => 5], ['foo' => 10]])->max('foo');

// The output is 10.

#4) min()

Description: This method returns the minimum value in the collection.

Example 1:

collect([1, 2, 3, 4, 5])->min();

// The output is 1.

Example 2:

$min = collect([['foo' => 5], ['foo' => 10]])->min('foo');

// The output is 5.

#5) pluck()

Description: This method returns all the values for a given key.

Example:

$collection = collect([
     ['student_id' => 'R001', 'name' => 'John'],
     ['student _id' => 'R002', 'name' => 'Bob'],
]);
$plucked = $collection->pluck('name');
$plucked->all();

// The output is [‘John’, ‘Bob’].

#6) sum()

Description: This method returns the sum of all items in the collection.

Example:

$sum = collect([1, 2, 3, 4, 5])->sum();

// The output is 15.

#7) avg()

Description: This method returns the average value of a given key.

Example:

$average = collect([1, 2, 3, 4, 5])->avg();

// The output is 3.

#8) push()

Description: This method appends an item to the end of the collection.

Example:

$collection = collect([1, 2, 3, 4, 5]);
$collection->push(6);
$collection->all();

// The output is [1, 2, 3, 4, 5, 6].

#9) pop()

Description: This method removes and returns the last item from the collection.

Example:

$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();

// The output is 5.

$collection->all();

// The output is [1, 2, 3, 4].

#10) random()

Description: This method returns a random item from the collection.

Example:

$collection = collect([1, 2, 3, 4, 5]);
$collection->random();

// The output is 2 (or any other item value from the collection).

#11) search()

Description: This method searches the collection for the given value. It will return its key if the item is found, and it will return false if the item is not found.

Example:

$collection = collect([2, 4, 6, 8]);
$collection->search(4);

// The output is 1.

#12) sort()

Description: This method sorts the collection.

Example:

$collection = collect([2, 1, 4, 5, 3]);
$sorted = $collection->sort();
$sorted->values()->all();

// The output is [1, 2, 3, 4, 5].

#13) count()

Description: This method returns the total number of items in the collection.

Example:

$collection = collect([1, 2, 3, 4, 5]);
$collection->count();

// The output is 5.

#14) isEmpty()

Description: This method returns true if the collection is empty and returns false if the collection is not empty.

Example:

collect([])->isEmpty();

// The output is true.

#15) dd()

Description: This method dumps items in the collection and ends the execution of the script.

Example:

$collection = collect(['Rahul', 'Sachin']);
$collection->dd();

/* The output is
   Collection {
        #items: array:2 [
           0 => "Rahul"
           1 => "Sachin"
         ]
      }
*/

Setting Up A Project For Laravel Collections

Let’s see how to set up a project for Laravel collections.

Step 1: Run the following command in the command prompt to create a new Laravel project named collection-tutorial.

composer create-project --prefer-dist laravel/laravel:^7.0 collection-tutorial

Step 2: Run the following command in the command prompt to create a command called CollectionCommand.

php artisan make:command CollectionCommand

The above command will create a file named CollectionCommand.php in the App/Console/Commands folder.

Step 3: Open the CollectionCommand.php file in the App/Console/Commands folder and modify the existing code as shown below:

<?php

namespace App\Console\Commands;
	
use Illuminate\Console\Command;

class CollectionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collection:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Laravel Test Collection';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        dd('success');
    }
}

Step 4: Open the Kernel.php file in the App/Console folder and modify the existing code as shown below:

<?php

namespace App\Console;

use App\Console\Commands\CollectionCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        CollectionCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Step 5: Run the following command in the command prompt.

php artisan

You will see your newly created command is present under the collection as shown in the below screenshot.

collection command

Step 6: Run the following command in the command prompt.

php artisan collection:test

If the above command successfully executed, you will get “success” as the output.

That’s it.

Laravel Collections Example

In this example, we have discussed how to create a Laravel collection and used the method first() to get a specific collection output. The method first() returns the first element in the collection.

Step 1: Run the following command in the command prompt to create a new Laravel project named collection-tutorial-2.

composer create-project --prefer-dist laravel/laravel:^7.0 collection-tutorial-2

Step 2: Run the following command in the command prompt to create a command called CollectionCommand.

php artisan make:command CollectionCommand

The above command will create a file named CollectionCommand.php in the App/Console/Commands folder.

Step 3: Open the CollectionCommand.php file in the App/Console/Commands folder and modify the existing code as shown below:

<?php

namespace App\Console\Commands;

use App\CollectionTest;

use Illuminate\Console\Command;

class CollectionCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collection:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Laravel Test Collection';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        dd((new CollectionTest())->test());
    }
}

Step 4: Open the Kernel.php file in the App/Console folder and modify the existing code as shown below:

<?php

namespace App\Console;

use App\Console\Commands\CollectionCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        CollectionCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Step 5: Create a new PHP file called CollectionTest.php inside the App folder and add the following code:

<?php

namespace App;

class CollectionTest
{
    public function test()
    {
        return collect(['a','b','c','d','e'])->first();
    }    
}

Note: Similarly, you can use any other available methods instead of the method first().

Step 6: Run the following command in the command prompt.

php artisan collection:test

If the above command gets successfully executed, you will get “a” as the output.

Laravel Forge

It is a server management and site deployment service for PHP applications. If you are not managing your own server, Laravel Forge is a great alternative. According to the Laravel Forge website, Forge is already managing more than 340,000 applications.

It can create servers on various platforms such as

  • DigitalOcean
  • Linode
  • Vultr
  • Amazon
  • Hetzner and more.

After connecting to Laravel Forge, it will install the following components:

  • Nginx
  • MySQL
  • Redis
  • Memcached, etc.

>>Visit the URL to go to the official website of Laravel Forge.

Advantages Of Laravel Forge

It has a lot of advantages. The following list shows some advantages of Laravel Forge:

  • Deploy applications in quick time.
  • Manage multiple versions of PHP on a single server.
  • Deploy script environment variables.
  • Support database backups.
  • Provide load balancer methods.
  • Provide password-protected paths within the Forge dashboard.
  • phpMyAdmin is available as a one-click installation.
  • Provide self-hosted GitLab support.
  • Provide high security.
  • Facility to send Telegram notifications to Telegram group chats.

Laravel Forge Pricing Plans

Laravel Forge is not free, but it provides affordable pricing plans. It offers three pricing plans named Hobby, Growth, and Business. It costs $12 per month, $19 per month, and $39 per month for the Hobby pricing plan, the Growth pricing plan, and the Business pricing plan, respectively.

All three pricing plans include features such as unlimited sites, unlimited deployments, and push to deploy. The Hobby pricing plan offers a single server while the Growth pricing plan and the Business pricing plan offer unlimited servers. Additionally, the Business pricing plan includes services such as share servers with teammates, database backups, and server metric monitoring.

Creating a Laravel Forge Account:

This account creation procedure is simple. Visit the URL to create a new Laravel Forge account.

Conclusion

Laravel collection is a convenient wrapper to work with array data. Several methods are available to work with Laravel collections.

Laravel Forge is a server management and site deployment service for PHP applications.

We hope you found this tutorial helpful! Hope to see you again in the next tutorial where we will discuss Laravel interview questions.

Happy learning!

<<PREV Tutorial | NEXT Tutorial>>

Was this helpful?

Thanks for your feedback!

Leave a Comment