Useful tips for Collection operations In Laravel

Let’s start with some really basic methods. For a better understanding of what you are going to do, I strongly suggest that you try on your project every single method from the following list:

  • The first is contains(). It returns true or false if a record with a certain ID is included in the collection.Here’s an example:
      $books = AppBook::all();
    
      if($books->contains(3))
      {
        return 'yeah, book 3 is here!';
      }

    All you have to do, here, is to specify the ID as a parameter.

  • As I told you earlier, you can use a collection as an array. So, if you want to get the third element in a collection, you can use this:
      $book = $books[2];
  • However, if you don’t like this syntax for some reason, you can use get() in an alternative way, like this:
      $book = $books->get(2);
  • With this powered syntax, you can also specify a default value if the desired index doesn’t exist:
      $book = $books->get(2, "Not Found!");
  • Obviously, you can check the existence of a specific element, if you want, with has():
      if($books->has(3))
      {
        $book = $books->get(3);
      }
  • $book = new Book;
      // other attributes assignment here...
    
      $books->put(2, $book);
    
    
    • As you may imagine, the first argument is the desired index, and the second argument is the value.
    • Another cool method is prepend(), which you can use to prepend an element to a certain collection. Here’s the syntax:
        $firstBook = new Book;
        // other attributes assignment here...
      
        $books->prepend($book);
    • If you want to get an array with all the primary keys, you can use a dedicated modelKeys() method!
        $books = AppBook::all();
      
        $primaryKeys = $books->modelKeys();

      It’s not over yet; actually, there are many methods you can use for many different things.

    • An example is random(), which extracts a single random item from the specified collection:
        $books = AppBook::all();
      
        $randomBook = $books->random();
    • Also, you can use keys() or values() to get arrays for only keys or values, respectively.
      $books = AppBook::all();
      
        $keysArray = $books->keys();
        $valuesArray = $books->values();
      
      • What? You want to treat your collection as a stack? No problem, pop() and push() are here to help!
          // let's get the last item!
          $books = AppBooks::all();
          $lastBook = $books->pop();
        
          // lets' add a new item ad the end!
          $book = new Book;
          // other attributes assignment here...
        
          $books->push($book);
      • Now, what about searching for an item in a collection using syntax similar to the here() you called on models? Take a look at this:
            $books = AppBook::all();
            
            $book = $books->where('title', 'Michael Strogoff');

        Note that this method returns another category. This means that you can use many chained calls of where(). Here’s another example that gives a better idea:

          $books = AppBook::all();
        
          $book = $categories->where('year', 1876)->where('page_count', 254);
          $books = AppBook::all();
        
          $secondPageBooks = $books->perPage(2, 10);

        With this simple call, you are getting 10 books, starting from the second page. I think this is a great example of expressive syntax of methods that Eloquent (and Laravel) offers.

        Note

        If you want to know more about the Collection class and what it offers, take a look at http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Collection.html or look directly at the code in IlluminateDatabaseEloquentCollection and IlluminateSupportCollection classes.

         

        As the opposite of get(), you can add an element with a specific index using put():

        Transforming collections

        Quite often, Eloquent automatically takes a collection to transform it into something that you can output in a better way. For example, here is the code that I am using to show a list of a magazine website’s news categories:

          $categories = AppCategory::all();
           return $categories;

        This is the corresponding output:

          [
            {
              id: 1,
              name: "Editorial",
              slug: "editorial",
              description: "Qui est quo asperiores aliquid vitae possimus. Dolor consequuntur similique voluptatem a laborum dolorem ea repellendus. Aspernatur ducimus quis dolorum consequatur vel nam at. Aut omnis rem laborum.",
              created_at: "2015-04-21 10:14:37",
              updated_at: "2015-04-21 10:14:37"
            },
            {
              id: 2,
              name: "Interview",
              slug: "interview",
              description: "Rerum deleniti rerum aliquid laudantium id non voluptatum. Aut quia distinctio consequatur velit natus inventore sunt iusto. Non totam quis quam sint et.",
              created_at: "2015-04-21 10:14:37",
              updated_at: "2015-04-21 10:14:37"
            },
            {
              id: 3,
              name: "Reportage",
              slug: "reportage",
              description: "Adipisci et veritatis excepturi ullam explicabo. Eos dolore quas a vero. Optio voluptatem accusamus ex optio. Rerum rem quaerat qui maiores.",
              created_at: "2015-04-21 10:14:37",
              updated_at: "2015-04-21 10:14:37"
            }
          ]

        However, now consider the following code:

          $categories = AppCategory::all();
           return $categories;

        Then, let’s change the code to this:

        $categories = AppCategory::all();
        dd($categories);
        

        This is what happens:

          Collection {#152
            #items: array:3 [
              0 => Category {#155
                #connection: null
                #table: null
                #primaryKey: "id"
                #perPage: 15
                +incrementing: true
                +timestamps: true
                #attributes: array:6 [
                  "id" => 1
                  "name" => "News"
                  "slug" => "news"
                  "description" => "Qui est quo asperiores aliquid vitae possimus. Dolor consequuntur similique voluptatem a laborum dolorem ea repellendus. Aspernatur ducimus quis dolorum consequatur vel nam at. Aut omnis rem laborum."
                  "created_at" => "2015-04-21 10:14:37"
                  "updated_at" => "2015-04-21 10:14:37"
                ]
                #original: array:6 [
                  "id" => 1
                  "name" => "News"
                  "slug" => "news"
                  "description" => "Qui est quo asperiores aliquid vitae possimus. Dolor consequuntur similique voluptatem a laborum dolorem ea repellendus. Aspernatur ducimus quis dolorum consequatur vel nam at. Aut omnis rem laborum."
                  "created_at" => "2015-04-21 10:14:37"
                  "updated_at" => "2015-04-21 10:14:37"
                ]
                #relations: []
                #hidden: []
                #visible: []
                #appends: []
                #fillable: []
                #guarded: array:1 [
                  0 => "*"
                ]
                #dates: []
                #casts: []
                #touches: []
                #observables: []
                #with: []
                #morphClass: null
                +exists: true
              }
              1 => Category {#156 ...}
              2 => Category {#157 ...}
            ]
          }

        Wait, wait; what? Just changing a dd() call with a return? Well, you can see this magic using two special methods: toArray and toJSON. You can also use them manually, if you need, just like this:

          $books = AppBook::all();
        
          $toArray = $books->toArray();
          $toJson = $books->toJson();

        Cool, right?

        Note

        The dd() function I used before is a Laravel utility. It’s a mix of the native PHP var_dump() and die(). To be more precise, it shows the value of a certain object or variable, and then stops the script.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

4 Comments
by Deven Rathore
5 min read

Pin It on Pinterest

Shares