← Other topics

Laravel In a Nutshell - Eloquent & Collections (#7)

Series contents:

Video Notes

In the previous part of this series, we learned how to create Eloquent Models to interact with our database tables. We put the model to use within Laravel’s database seeding system to enter sample data into our database.

In this guide, we see more examples of working with Eloquent, putting it to use within features of our application.

Specifically, we’ll rewrite our “show products by category” page so that instead of getting our products data from our hard-coded array, we retrieve the data from the database:

/**
 * GET /products/{category?}
 */
public function showProductsByCategory($category = null)
{
    # This will return us a Collection of all the categories in the database
    $categories = Category::all();

    $products = null;
    
    # Only attempt to narrow down products by category if a category was included as part of the URL
    if($category) {
       
        # First, we have to find the id for the requested category
        # Now how we’re getting this info by querying the existing Collection (retrieved above)
        $category_id = $categories->firstWhere('name', $category)->id;

        # Now we can query for products matching this category
        $products = Product::where('category_id', $category_id)->get();
    }

    return view('products')
        ->with('products', $products)
        ->with('category', $category)
        ->with('categories', $categories);
}

The above code demonstrates how Eloquent queries often return a Laravel data type called a Collection. Collections contain not only the data retrieved from the database, but many methods for working with that data.

The above code also demonstrates different Eloquent methods used to build queries including all, where, and get. Below is a selection of other Eloquent methods you’ll encounter when building queries. Be sure to reference the Eloquent docs for a more comprehensive list and details on all of these methods.

Retrieving Models:

  • get()
  • first()
  • find($id)
  • findOrFail($id)
  • findOrNew($id)
  • pluck($column)
  • select($columns)
  • distinct()

Conditions:

  • where($column, $operator, $value)
  • orWhere($column, $operator, $value)
  • whereIn($column, $values)
  • orWhereIn($column, $values)
  • whereBetween($column, [$min, $max])
  • orWhereBetween($column, [$min, $max])
  • whereNull($column)
  • orWhereNull($column)
  • whereNotNull($column)
  • orWhereNotNull($column)
  • whereDate($column, $operator, $value)
  • orWhereDate($column, $operator, $value)
  • whereTime($column, $operator, $value)
  • orWhereTime($column, $operator, $value)
  • whereYear($column, $year)
  • orWhereYear($column, $year)
  • whereMonth($column, $month)
  • orWhereMonth($column, $month)
  • whereDay($column, $day)
  • orWhereDay($column, $day)

Ordering:

  • orderBy($column, $direction)
  • latest()
  • oldest()

Aggregates:

  • count()
  • sum($column)
  • avg($column)
  • min($column)
  • max($column)

Grouping:

  • groupBy($column)
  • having($column, $operator, $value)

Joins:

  • join($table, $first, $operator, $second)
  • leftJoin($table, $first, $operator, $second)
  • rightJoin($table, $first, $operator, $second)
  • crossJoin($table)
  • joinWhere($table, Closure $callback, $first = null, $operator = null, $second = null)

Relationships:

  • with($relations)
  • has($relation)
  • doesntHave($relation)
  • whereHas($relation, Closure $callback)
  • orWhereHas($relation, Closure $callback)
  • withCount($relations)

Inserts, Updates, and Deletes:

  • insert($data)
  • update($data)
  • delete()
  • forceDelete()
If this info helped you out, you can send a tip via PayPal. Thanks for your support!
← Other topics