Eloquent provides relationship methods and eager loading with with() to fetch related data efficiently. This reduces the number of queries and simplifies code.
use App\Models\User; $user = User::find(1); return $user->posts->count();
By default, the User model does not have a posts relationship unless explicitly defined. Trying to access $user->posts without defining it causes an error.
Option C correctly finds the user, sets the email attribute, and saves the model. Option C has wrong method chaining order. Option C uses a non-existent method. Option C assigns to a wrong property.
use App\Models\User; $users = User::where('active', true)->get(); $names = $users->pluck('name'); return $names->toArray();
pluck do on an Eloquent collection?The pluck method extracts the values of a given key from the collection. Here, it returns the names of active users as an array.
use App\Models\Post; $posts = Post::where('published', true)->get(); foreach ($posts as $post) { echo $post->author->name; }
author relationship defined.If the author relationship is missing, $post->author returns null, and trying to access name on null causes an error.