LARAVEL LARAVEL Eloquent ORM & Database 1 — Questions and Answers
Question 1: What class must a Laravel Eloquent model extend?
- Illuminate\Database\Eloquent\Model (Correct answer)
- Illuminate\Database\Query\Builder
- Illuminate\Database\Eloquent\Collection
- Illuminate\Support\Facades\DB
Correct answer: Illuminate\Database\Eloquent\Model
All Eloquent models must extend the base Illuminate\Database\Eloquent\Model class to gain ORM functionality.
Question 2: Which Eloquent method retrieves all records from a database table?
- Model::all() (Correct answer)
- Model::get()
- Model::fetch()
- Model::list()
Correct answer: Model::all()
Model::all() returns an Eloquent Collection containing every record in the model's corresponding database table.
Question 3: What is the purpose of the `$fillable` property in an Eloquent model?
- To whitelist attributes that are mass-assignable (Correct answer)
- To list columns that should be hidden from JSON output
- To define the primary key columns
- To specify columns that trigger model events
Correct answer: To whitelist attributes that are mass-assignable
The $fillable array guards against mass-assignment vulnerabilities by explicitly allowing only listed attributes to be set via create() or fill().
Question 4: Which Eloquent method finds a model by its primary key and throws an exception if not found?
- findOrFail() (Correct answer)
- find()
- firstOrFail()
- getOrFail()
Correct answer: findOrFail()
findOrFail() retrieves a model by primary key and throws a ModelNotFoundException if no record exists.
Question 5: How do you define a one-to-many relationship in Eloquent from the parent model?
- public function children() { return $this->hasMany(Child::class); } (Correct answer)
- public function children() { return $this->belongsToMany(Child::class); }
- public function children() { return $this->hasOne(Child::class); }
- public function children() { return $this->manyTo(Child::class); }
Correct answer: public function children() { return $this->hasMany(Child::class); }
The hasMany() method defines a one-to-many relationship where the current model is the parent with multiple related records.
Question 6: What does eager loading with `with()` prevent in Laravel?
- The N+1 query problem (Correct answer)
- SQL injection attacks
- Duplicate model instances
- Cross-database queries
Correct answer: The N+1 query problem
Eager loading via with() loads related models in a fixed number of queries rather than issuing a new query for each parent record, solving the N+1 problem.
What class must a Laravel Eloquent model extend?