Querying with Eloquent

Fetch records with all(), find(), where() and get().

SyntaxPost::where('column', $value)->get();

Eloquent gives every model expressive query methods:

  • Post::all() — every row.
  • Post::find(1) — by primary key.
  • Post::where('active', true)->get() — filtered.
  • Post::first() — the first match.

Query results come back as Collections, so all the collection methods you learned apply.

Example

Example · php
// Fetch published posts, newest first:
$posts = Post::where('published', true)
    ->orderBy('created_at', 'desc')
    ->take(10)
    ->get();

When to use it

  • An admin dashboard queries only active products sorted by price using method chaining to keep the query intention readable in the controller.
  • A search endpoint combines where(), orWhere(), and like to filter posts by title or body content based on the user's search term.
  • A reporting page uses selectRaw() with groupBy() to aggregate order totals by month directly in the database rather than in PHP.

More examples

Chained where clauses

Chains where(), orderBy(), and limit() to build a query that fetches the cheapest 20 active products.

Example · php
$products = Product::where('is_active', true)
    ->where('price', '<=', 100)
    ->orderBy('price')
    ->limit(20)
    ->get();

// Equivalent using query scope shorthand
$products = Product::active()->cheap()->latest()->take(20)->get();

Search with like and orWhere

Wraps the OR conditions in a grouped closure so the outer AND (published = true) is not broken by the OR.

Example · php
$term = $request->input('q', '');

$posts = Post::where(function ($query) use ($term) {
        $query->where('title', 'like', "%{$term}%")
              ->orWhere('body',  'like', "%{$term}%");
    })
    ->where('published', true)
    ->latest()
    ->paginate(15);

Aggregate with selectRaw and groupBy

Uses selectRaw() and groupByRaw() to let the database compute monthly revenue totals without loading individual order rows into PHP.

Example · php
$monthly = Order::selectRaw(
        'YEAR(created_at)  AS year,
         MONTH(created_at) AS month,
         SUM(total)        AS revenue,
         COUNT(*)          AS order_count'
    )
    ->where('status', 'completed')
    ->groupByRaw('YEAR(created_at), MONTH(created_at)')
    ->orderByRaw('year DESC, month DESC')
    ->get();

Discussion

  • Be the first to comment on this lesson.