Bird
0
0

You want to retrieve all users who have made at least one order using Laravel Eloquent. Which approach correctly uses database integration to achieve this?

hard📝 component behavior Q8 of 15
Laravel - Database Basics and Migrations
You want to retrieve all users who have made at least one order using Laravel Eloquent. Which approach correctly uses database integration to achieve this?
AUser::has('orders')->get();
BUser::where('orders', '>', 0)->get();
CUser::with('orders')->count();
DUser::all()->filter(fn($u) => $u->orders > 0);
Step-by-Step Solution
Solution:
  1. Step 1: Understand Eloquent relationship queries

    'has' method filters models with related records, perfect for users with orders.
  2. Step 2: Evaluate options

    with('orders')->count() returns a count of all users without filtering by existence of orders; where('orders', '>', 0)->get() incorrectly treats 'orders' as a column; all()->filter(fn($u) => $u->orders > 0) loads all users then filters inefficiently in PHP (and collection comparison may fail). Only User::has('orders')->get(); correctly filters and retrieves at the database level.
  3. Final Answer:

    User::has('orders')->get(); -> Option A
  4. Quick Check:

    Use 'has' for related records = User::has('orders')->get(); [OK]
Quick Trick: Use 'has' to filter models with related records [OK]
Common Mistakes:
  • Treating relationships as columns
  • Counting instead of retrieving models
  • Filtering after loading all records

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes