MCQs of Day 7 Eloquent ORM Basics

 MCQs of Day 7

Eloquent ORM Basics

1. Which command is used to create an Eloquent model in Laravel?

A) php artisan create:model
B) php artisan make:model
C) php artisan model:create
D) php artisan generate:model

Answer: B) php artisan make:model
Explanation: The php artisan make:model command is used to create a new Eloquent model in Laravel.


2. What is the purpose of the $fillable property in an Eloquent model?

A) To define which fields can be mass-assigned
B) To define the table name
C) To store timestamps
D) To define relationships between models

Answer: A) To define which fields can be mass-assigned
Explanation: The $fillable property in an Eloquent model defines which fields are allowed for mass-assignment to protect against mass-assignment vulnerabilities.


3. How do you retrieve a single record by its ID in Eloquent?

A) Model::get(1)
B) Model::find(1)
C) Model::single(1)
D) Model::first(1)

Answer: B) Model::find(1)
Explanation: The find() method retrieves a single record by its primary key (ID).


4. What does the save() method do in Eloquent?

A) Inserts a new record in the database
B) Updates the existing record in the database
C) Both inserts and updates a record
D) Deletes the record from the database

Answer: C) Both inserts and updates a record
Explanation: The save() method either inserts a new record or updates an existing one, depending on whether the model already has an ID.


5. Which method is used to insert a new record in Eloquent?

A) insert()
B) create()
C) store()
D) add()

Answer: B) create()
Explanation: The create() method is used to insert a new record into the database in Eloquent.


6. How do you check if a model exists in the database?

A) Model::find()
B) Model::exists()
C) Model::has()
D) Model::check()

Answer: B) Model::exists()
Explanation: The exists() method checks if any records exist that match a given query.


7. How do you retrieve all records from a table using Eloquent?

A) Model::all()
B) Model::get()
C) Model::fetch()
D) Model::select()

Answer: A) Model::all()
Explanation: The all() method retrieves all records from the model's associated table.


8. What does the pluck() method do in Eloquent?

A) Retrieves the first record
B) Retrieves a single column's value from a collection
C) Deletes a record
D) Inserts a new record

Answer: B) Retrieves a single column's value from a collection
Explanation: The pluck() method is used to retrieve values from a specific column(s) from the model's database table.


9. What is the default table name used by an Eloquent model?

A) The name of the model
B) The pluralized form of the model name
C) The singular form of the model name
D) models table

Answer: B) The pluralized form of the model name
Explanation: By default, Laravel uses the plural form of the model's name as the table name (e.g., Product model uses products table).


10. Which method is used to retrieve the first record from a query in Eloquent?

A) get()
B) first()
C) all()
D) single()

Answer: B) first()
Explanation: The first() method retrieves the first record that matches the query.


11. How do you retrieve products with a price greater than 1000 using Eloquent?

A) Product::where('price', '>', 1000)->get()
B) Product::filter('price', '>', 1000)
C) Product::get('price', '>', 1000)
D) Product::find('price', '>', 1000)

Answer: A) Product::where('price', '>', 1000)->get()
Explanation: The where() method is used to filter records based on a given condition. The get() method retrieves all matching records.


12. Which method in Eloquent is used to update an existing record in the database?

A) save()
B) update()
C) create()
D) insert()

Answer: B) update()
Explanation: The update() method is used to update records in the database.


13. What method is used to delete a record in Eloquent?

A) remove()
B) delete()
C) destroy()
D) erase()

Answer: B) delete()
Explanation: The delete() method is used to delete a record in the database.


14. Which of the following methods is used for pagination in Eloquent?

A) paginate()
B) limit()
C) slice()
D) chunk()

Answer: A) paginate()
Explanation: The paginate() method is used to retrieve a set of results for pagination.


15. What does the chunk() method do in Eloquent?

A) Retrieves all records in batches
B) Retrieves a single record
C) Deletes records in batches
D) Updates records in batches

Answer: A) Retrieves all records in batches
Explanation: The chunk() method processes records in smaller chunks, making it more memory-efficient when dealing with large datasets.


16. How can you retrieve records sorted by a column in Eloquent?

A) orderBy()
B) sort()
C) by()
D) arrange()

Answer: A) orderBy()
Explanation: The orderBy() method is used to sort query results by a given column.


17. How do you check if a product with a specific name exists in Eloquent?

A) Model::check('name')
B) Model::exists('name')
C) Model::where('name', 'value')->exists()
D) Model::find('name')

Answer: C) Model::where('name', 'value')->exists()
Explanation: The exists() method is used to check if any records exist that match the given condition.


18. What method is used to define a one-to-many relationship in Eloquent?

A) hasOne()
B) belongsTo()
C) hasMany()
D) manyToMany()

Answer: C) hasMany()
Explanation: The hasMany() method is used to define a one-to-many relationship in Eloquent, where one model has many related models.


19. How do you retrieve products where the price is less than 500 and name contains 'Laptop'?

A) Product::where('price', '<', 500)->orWhere('name', 'like', '%Laptop%')
B) Product::find('price', '<', 500, 'name', 'like', '%Laptop%')
C) Product::filter('price', '<', 500, 'name', 'contains', 'Laptop')
D) Product::get('price', '<', 500, 'name', '%Laptop%')

Answer: A) Product::where('price', '<', 500)->orWhere('name', 'like', '%Laptop%')
Explanation: The where() method filters by price, and orWhere() is used to apply an additional condition for name matching.


20. Which Eloquent method is used to find a record by a given column other than the primary key?

A) findOrFail()
B) where()
C) pluck()
D) firstWhere()

Answer: B) where()
Explanation: The where() method is used to filter records by any column, including those other than the primary key.


21. What does the create() method do in Eloquent?

A) Updates a record if it exists, otherwise creates a new record
B) Inserts a new record into the database
C) Retrieves data from the database
D) Deletes a record from the database

Answer: B) Inserts a new record into the database
Explanation: The create() method is used to insert a new record into the database.


22. What is the correct syntax to update a product's price in Eloquent?

A) Product::update('price', 1500)
B) Product::set('price', 1500)
C) $product->update(['price' => 1500])
D) Product::change('price', 1500)

Answer: C) $product->update(['price' => 1500])
Explanation: To update an existing record, you can use the update() method on an instance of the model, passing an array of column values.


23. How do you define a many-to-many relationship in Eloquent?

A) hasMany()
B) belongsToMany()
C) hasOne()
D) manyToMany()

Answer: B) belongsToMany()
Explanation: The belongsToMany() method is used to define a many-to-many relationship between two models in Eloquent.


24. What is the purpose of the $guarded property in an Eloquent model?

A) To prevent mass-assignment for specific attributes
B) To define which fields can be mass-assigned
C) To define table relationships
D) To store timestamps

Answer: A) To prevent mass-assignment for specific attributes
Explanation: The $guarded property defines which attributes are not mass-assignable, offering an alternative to $fillable.


25. How can you retrieve products with a specific category using Eloquent relationships?

A) $product->category
B) Product::category()->get()
C) Product::where('category', 'value')->get()
D) Category::products()->get()

Answer: A) $product->category
Explanation: In a one-to-many relationship, you can retrieve related records by accessing the relationship method, like $product->category.


26. What does the findOrFail() method do in Eloquent?

A) Returns null if the record is not found
B) Throws a 404 error if the record is not found
C) Returns an empty array if the record is not found
D) Returns the first record

Answer: B) Throws a 404 error if the record is not found
Explanation: The findOrFail() method attempts to retrieve a record by its primary key and throws a ModelNotFoundException if the record is not found.


(Continuing in the next part due to space constraints.)

4o mini

You said:

more

ChatGPT said:

ChatGPT

Continuing with the remaining MCQs:


27. Which Eloquent method allows you to get the first record matching a condition?

A) first()
B) get()
C) find()
D) single()

Answer: A) first()
Explanation: The first() method retrieves the first record that matches the given condition.


28. How do you retrieve the last record from a query in Eloquent?

A) last()
B) getLast()
C) orderBy('created_at', 'desc')->first()
D) latest()->first()

Answer: C) orderBy('created_at', 'desc')->first()
Explanation: To get the last record, we use orderBy('created_at', 'desc') to order records by descending date and then use first() to retrieve the last one.


29. What does the with() method do in Eloquent?

A) Eager loads relationships
B) Performs a query with multiple conditions
C) Filters records based on related models
D) Updates records in batches

Answer: A) Eager loads relationships
Explanation: The with() method is used to eager load related models, minimizing the number of queries needed for retrieving related data.


30. What is the function of the has() method in Eloquent relationships?

A) Checks if a relationship exists for a model
B) Defines the inverse of a relationship
C) Creates a new related record
D) Fetches related data

Answer: A) Checks if a relationship exists for a model
Explanation: The has() method is used to filter results based on the existence of a related model.


31. Which of the following is correct to define a belongsTo relationship in Eloquent?

A) public function category() { return $this->belongsTo('App\Category'); }
B) public function category() { return $this->hasMany('App\Category'); }
C) public function category() { return $this->hasOne('App\Category'); }
D) public function category() { return $this->belongsToMany('App\Category'); }

Answer: A) public function category() { return $this->belongsTo('App\Category'); }
Explanation: The belongsTo relationship is defined when the current model belongs to another model, typically used for foreign key relationships.


32. How do you retrieve only specific columns from a table in Eloquent?

A) Model::select('column1', 'column2')->get()
B) Model::get('column1', 'column2')
C) Model::find('column1', 'column2')
D) Model::columns('column1', 'column2')->get()

Answer: A) Model::select('column1', 'column2')->get()
Explanation: The select() method is used to specify which columns to retrieve from the database.


33. Which Eloquent method allows you to apply conditions to a relationship query?

A) where()
B) with()
C) has()
D) hasMany()

Answer: B) with()
Explanation: The with() method allows you to eager load relationships with conditions applied.


34. How do you delete a record by its ID using Eloquent?

A) Model::deleteById(1)
B) Model::find(1)->delete()
C) Model::delete(1)
D) Model::destroy(1)

Answer: B) Model::find(1)->delete()
Explanation: First, the record is retrieved using find(), and then delete() is called on the model instance.


35. Which method would you use to retrieve the count of records for a given condition in Eloquent?

A) count()
B) total()
C) records()
D) size()

Answer: A) count()
Explanation: The count() method is used to retrieve the number of records that match a specific query condition.


36. What does the pluck() method return in Eloquent?

A) A single column's values from the collection
B) A key-value pair of the entire record
C) An array of all columns
D) A paginated collection

Answer: A) A single column's values from the collection
Explanation: The pluck() method returns an array of values for a specific column from the database.


37. What is the correct way to define an inverse hasOne relationship in Eloquent?

A) public function product() { return $this->hasOne('App\Product'); }
B) public function product() { return $this->belongsTo('App\Product'); }
C) public function product() { return $this->hasMany('App\Product'); }
D) public function product() { return $this->belongsToMany('App\Product'); }

Answer: B) public function product() { return $this->belongsTo('App\Product'); }
Explanation: The inverse of a hasOne relationship is typically defined with belongsTo().


38. How do you use a where condition with a hasMany relationship?

A) Model::hasMany()->where('column', 'value')
B) Model::where('column', 'value')->hasMany()
C) Model::whereHas('relation', function($query) { $query->where('column', 'value'); })
D) Model::with('relation')->where('column', 'value')

Answer: C) Model::whereHas('relation', function($query) { $query->where('column', 'value'); })
Explanation: The whereHas() method is used to add conditions to a relationship query.


39. What does the create() method require in Eloquent?

A) An array of attributes and their values
B) A model instance
C) The table name
D) The database connection

Answer: A) An array of attributes and their values
Explanation: The create() method requires an array of attributes that should be inserted into the database.


40. What method is used to attach a model to a many-to-many relationship in Eloquent?

A) attach()
B) add()
C) addMany()
D) link()

Answer: A) attach()
Explanation: The attach() method is used to add a record to a many-to-many relationship.


41. Which of the following will return records where the name is like 'foo%' using Eloquent?

A) Model::where('name', 'foo%')->get()
B) Model::like('name', 'foo%')->get()
C) Model::where('name', 'like', 'foo%')->get()
D) Model::find('name', 'foo%')->get()

Answer: C) Model::where('name', 'like', 'foo%')->get()
Explanation: The where() method with like is used to filter records based on pattern matching.


42. How do you retrieve the average of a column in Eloquent?

A) Model::average('column')
B) Model::avg('column')
C) Model::mean('column')
D) Model::aggregate('column')

Answer: B) Model::avg('column')
Explanation: The avg() method retrieves the average value of a column.


43. How do you prevent a model from being timestamped in Eloquent?

A) $timestamps = false;
B) $timestamps = true;
C) $timestamps = 'no';
D) $timestamps = null;

Answer: A) $timestamps = false;
Explanation: Setting $timestamps = false; in the model prevents Eloquent from automatically managing created_at and updated_at timestamps.


44. Which method allows you to update a model using an array of attributes?

A) update()
B) fill()
C) updateAttributes()
D) set()

Answer: B) fill()
Explanation: The fill() method is used to fill a model with an array of attributes, which can then be saved.


45. How do you retrieve all records ordered by the created_at column in ascending order?

A) Model::orderBy('created_at', 'asc')->get()
B) Model::orderBy('created_at')->get()
C) Model::asc('created_at')->get()
D) Model::orderby('created_at')->get()

Answer: A) Model::orderBy('created_at', 'asc')->get()
Explanation: The orderBy() method sorts records based on a specific column in ascending or descending order.


46. What is the purpose of the findOrFail() method in Eloquent?

A) To fetch a record by its primary key and throw an exception if not found
B) To fetch a record by its primary key and return null if not found
C) To fetch multiple records based on primary keys
D) To check if a record exists

Answer: A) To fetch a record by its primary key and throw an exception if not found
Explanation: findOrFail() tries to find a record by its primary key and throws an exception (ModelNotFoundException) if the record is not found.


These are just a selection of MCQs based on the Eloquent ORM concepts. Let me know if you'd like more or need further details!

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs based on Eloquent ORM concepts:


47. What method is used to retrieve a single model instance by its primary key in Eloquent?

A) find()
B) first()
C) get()
D) retrieve()

Answer: A) find()
Explanation: The find() method is used to retrieve a single model instance by its primary key.


48. What does the save() method do in Eloquent?

A) Saves a new model to the database
B) Updates an existing model in the database
C) Saves a new or updates an existing model in the database
D) Saves a model only if it has been modified

Answer: C) Saves a new or updates an existing model in the database
Explanation: The save() method is used to persist a new model or update an existing one to the database.


49. How do you retrieve all records from a table using Eloquent?

A) Model::all()
B) Model::getAll()
C) Model::get()
D) Model::findAll()

Answer: A) Model::all()
Explanation: The all() method retrieves all records from the corresponding table as a collection of model instances.


50. How do you prevent a model from being mass-assigned in Eloquent?

A) $guarded = ['column1', 'column2'];
B) $fillable = ['column1', 'column2'];
C) $guarded = false;
D) $massAssigment = false;

Answer: A) $guarded = ['column1', 'column2'];
Explanation: The $guarded property specifies which attributes are not mass-assignable, preventing mass-assignment vulnerabilities.


51. Which Eloquent method is used to delete a record by its primary key?

A) Model::delete(1)
B) Model::destroy(1)
C) Model::remove(1)
D) Model::deleteById(1)

Answer: B) Model::destroy(1)
Explanation: The destroy() method is used to delete a record by its primary key.


52. What method would you use to retrieve a record with a specific condition in Eloquent?

A) find()
B) where()
C) get()
D) first()

Answer: B) where()
Explanation: The where() method is used to apply a condition to a query. You can chain get() or first() to retrieve results.


53. Which method is used to retrieve records where a column value is greater than a specified value?

A) whereGreaterThan()
B) where('column', '>', value)
C) greaterThan()
D) column('>', value)

Answer: B) where('column', '>', value)
Explanation: The where() method with a comparison operator is used to retrieve records where a column value is greater than a specified value.


54. What method allows you to get the sum of a column in Eloquent?

A) total()
B) sum()
C) aggregate()
D) count()

Answer: B) sum()
Explanation: The sum() method retrieves the total sum of values in a given column.


55. How do you define a hasMany relationship in Eloquent?

A) public function posts() { return $this->hasMany('App\Post'); }
B) public function posts() { return $this->belongsTo('App\Post'); }
C) public function posts() { return $this->hasOne('App\Post'); }
D) public function posts() { return $this->belongsToMany('App\Post'); }

Answer: A) public function posts() { return $this->hasMany('App\Post'); }
Explanation: The hasMany() method defines a one-to-many relationship, where one model can have many related models.


56. What is the function of the timestamps property in an Eloquent model?

A) To automatically manage the created_at and updated_at columns
B) To define the table columns
C) To set a column for storing the last modification timestamp
D) To disable the use of timestamps for a model

Answer: A) To automatically manage the created_at and updated_at columns
Explanation: Eloquent automatically maintains the created_at and updated_at columns unless explicitly disabled by setting $timestamps = false.


57. What method can you use to eager load a relationship in Eloquent?

A) load()
B) eagerLoad()
C) with()
D) retrieve()

Answer: C) with()
Explanation: The with() method is used for eager loading relationships to reduce the number of queries made when accessing related models.


58. What is the function of the increment() method in Eloquent?

A) Increases the value of a column by a specified amount
B) Retrieves the next value of an auto-increment field
C) Inserts a new record with an incremented ID
D) Updates a column by incrementing its value

Answer: A) Increases the value of a column by a specified amount
Explanation: The increment() method is used to increase the value of a column by a specified amount.


59. How would you retrieve the first 5 records from a table using Eloquent?

A) Model::limit(5)->get()
B) Model::take(5)->get()
C) Model::first(5)
D) Model::get(5)

Answer: B) Model::take(5)->get()
Explanation: The take() method is used to limit the number of records returned, followed by get() to retrieve the records.


60. Which Eloquent method is used to retrieve the last record based on a condition?

A) last()
B) latest()
C) findLast()
D) orderBy('column', 'desc')->first()

Answer: D) orderBy('column', 'desc')->first()
Explanation: To retrieve the last record based on a condition, you can use orderBy('column', 'desc')->first().


61. How would you define a polymorphic relationship in Eloquent?

A) Using morphTo()
B) Using morphMany()
C) Using morphOne()
D) Using morphMany() and morphTo()

Answer: D) Using morphMany() and morphTo()
Explanation: Polymorphic relationships are defined using morphMany() or morphOne() on the related model, and morphTo() on the parent model.


62. Which method is used to filter records based on the existence of a relationship in Eloquent?

A) whereExists()
B) whereHas()
C) hasMany()
D) filterExists()

Answer: B) whereHas()
Explanation: The whereHas() method is used to filter results based on the existence of a relationship.


63. What method is used to retrieve the latest records by date in Eloquent?

A) latest()
B) recent()
C) orderBy('created_at', 'desc')
D) newest()

Answer: A) latest()
Explanation: The latest() method retrieves records ordered by the created_at column in descending order.


64. What Eloquent method is used to add custom conditions to a relationship query?

A) whereHas()
B) filter()
C) hasWhere()
D) withWhere()

Answer: A) whereHas()
Explanation: The whereHas() method allows you to apply custom conditions to a relationship query.


65. Which method is used to check if a record exists in Eloquent?

A) exists()
B) find()
C) isEmpty()
D) hasRecord()

Answer: A) exists()
Explanation: The exists() method checks if at least one record matches the query conditions.


66. How would you define a one-to-one relationship in Eloquent?

A) public function profile() { return $this->hasOne('App\Profile'); }
B) public function profile() { return $this->belongsTo('App\Profile'); }
C) public function profile() { return $this->hasMany('App\Profile'); }
D) public function profile() { return $this->morphOne('App\Profile'); }

Answer: A) public function profile() { return $this->hasOne('App\Profile'); }
Explanation: The hasOne() method defines a one-to-one relationship, where the current model has a related model.


These are additional MCQs to further test and reinforce understanding of Eloquent ORM in Laravel. Let me know if you'd like more!

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs on Eloquent ORM concepts:


67. Which method is used to update a record's attributes in Eloquent without saving the model?

A) update()
B) touch()
C) save()
D) set()

Answer: A) update()
Explanation: The update() method allows you to update the attributes of a record without saving the model instance.


68. How do you retrieve the first record that matches a given condition in Eloquent?

A) findFirst()
B) first()
C) retrieveFirst()
D) getFirst()

Answer: B) first()
Explanation: The first() method is used to retrieve the first record that matches a given condition.


69. What does the pluck() method do in Eloquent?

A) Retrieves a single column from the database
B) Retrieves all columns of a model
C) Retrieves the first record from a relationship
D) Retrieves a collection of models

Answer: A) Retrieves a single column from the database
Explanation: The pluck() method is used to retrieve a single column's values from the database as an array.


70. How do you apply sorting on multiple columns in Eloquent?

A) orderBy('column1', 'desc')->orderBy('column2', 'asc')
B) sortBy('column1', 'desc', 'column2', 'asc')
C) sortByMultiColumns('column1', 'column2')
D) sortBy('column1', 'column2')

Answer: A) orderBy('column1', 'desc')->orderBy('column2', 'asc')
Explanation: To sort by multiple columns in Eloquent, chain multiple orderBy() methods.


71. Which method is used to perform a "left join" on related models in Eloquent?

A) join()
B) leftJoin()
C) with()
D) joinWith()

Answer: B) leftJoin()
Explanation: The leftJoin() method is used to perform a left join on related models in Eloquent queries.


72. How can you get the number of records in a table using Eloquent?

A) count()
B) getCount()
C) total()
D) numRows()

Answer: A) count()
Explanation: The count() method is used to get the number of records in a table or collection.


73. What is the purpose of the forceDelete() method in Eloquent?

A) Deletes a record permanently without considering soft deletes
B) Marks a record as deleted but does not remove it
C) Deletes a record but only if it was previously soft deleted
D) Deletes a record and removes it from the database

Answer: A) Deletes a record permanently without considering soft deletes
Explanation: The forceDelete() method is used to delete a model permanently, bypassing any soft delete functionality.


74. What does the withTrashed() method do in Eloquent?

A) Includes soft-deleted records in the query results
B) Excludes soft-deleted records from the query results
C) Allows soft-deleted records to be permanently deleted
D) Makes the model soft-deletable

Answer: A) Includes soft-deleted records in the query results
Explanation: The withTrashed() method includes soft-deleted records in the query results, which would normally be excluded.


75. How can you define a belongsTo relationship in Eloquent?

A) public function user() { return $this->belongsTo('App\User'); }
B) public function user() { return $this->hasOne('App\User'); }
C) public function user() { return $this->hasMany('App\User'); }
D) public function user() { return $this->morphTo('App\User'); }

Answer: A) public function user() { return $this->belongsTo('App\User'); }
Explanation: The belongsTo() method defines an inverse one-to-many relationship where the current model belongs to another model.


76. What does the delete() method do in Eloquent?

A) Soft deletes a record and removes it from the database
B) Deletes a record from the database permanently
C) Marks a record as deleted in the database
D) Removes a model instance from memory without affecting the database

Answer: B) Deletes a record from the database permanently
Explanation: The delete() method removes a record permanently from the database unless soft deletes are enabled.


77. How do you add a custom query condition on a related model using Eloquent?

A) whereHas()
B) withWhere()
C) addQueryCondition()
D) filterHas()

Answer: A) whereHas()
Explanation: The whereHas() method is used to add custom query conditions to a related model.


78. How do you apply a "group by" condition in Eloquent?

A) groupBy()
B) groupByColumns()
C) aggregateBy()
D) group()

Answer: A) groupBy()
Explanation: The groupBy() method is used to group results by one or more columns in Eloquent queries.


79. What does the select() method do in Eloquent?

A) Defines which columns to retrieve
B) Selects the first record in a collection
C) Chooses columns for sorting
D) Limits the number of records returned

Answer: A) Defines which columns to retrieve
Explanation: The select() method specifies which columns should be included in the query results.


80. What does the firstOrFail() method do in Eloquent?

A) Retrieves the first matching record or throws a ModelNotFoundException if not found
B) Retrieves the first record or returns a default value if not found
C) Retrieves the first record and sets a flag if it is the last record
D) Finds the first record and returns null if not found

Answer: A) Retrieves the first matching record or throws a ModelNotFoundException if not found
Explanation: The firstOrFail() method retrieves the first matching record and throws a ModelNotFoundException if no record is found.


81. What is the default behavior of Eloquent when saving a model?

A) Eloquent always creates a new record
B) Eloquent updates the existing record if it already exists, or creates a new one
C) Eloquent only updates the record if it exists
D) Eloquent only saves the record if all attributes are non-null

Answer: B) Eloquent updates the existing record if it already exists, or creates a new one
Explanation: When saving a model, Eloquent will update an existing record if it already exists (determined by the primary key), or it will create a new record if no such model exists.


82. How do you update a record by its primary key in Eloquent?

A) Model::find(id)->update(attributes)
B) Model::updateById(id, attributes)
C) Model::update(id, attributes)
D) Model::update(id)->attributes()

Answer: A) Model::find(id)->update(attributes)
Explanation: To update a record, use find() to retrieve the record by its primary key and then call update() on the model instance.


83. How do you define a belongsToMany relationship in Eloquent?

A) public function roles() { return $this->belongsToMany('App\Role'); }
B) public function roles() { return $this->hasMany('App\Role'); }
C) public function roles() { return $this->hasOne('App\Role'); }
D) public function roles() { return $this->morphMany('App\Role'); }

Answer: A) public function roles() { return $this->belongsToMany('App\Role'); }
Explanation: The belongsToMany() method is used to define a many-to-many relationship between two models.


84. What does the touch() method do in Eloquent?

A) Updates the created_at timestamp of a model
B) Updates the updated_at timestamp of a model without modifying other attributes
C) Retrieves the most recent timestamp of a model
D) Deletes a record but retains its timestamp

Answer: B) Updates the updated_at timestamp of a model without modifying other attributes
Explanation: The touch() method updates the updated_at timestamp of a model, useful when you need to indicate that the model was recently modified without changing other attributes.


These additional MCQs cover more aspects of Eloquent ORM in Laravel. Let me know if you need more!

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are additional MCQs on Eloquent ORM concepts:


85. What is the main purpose of the hasMany relationship in Eloquent?

A) Defines a one-to-one relationship
B) Defines a many-to-one relationship
C) Defines a one-to-many relationship
D) Defines a many-to-many relationship

Answer: C) Defines a one-to-many relationship
Explanation: The hasMany() method defines a one-to-many relationship where a model can have many related models.


86. What does the chunk() method do in Eloquent?

A) Retrieves a chunk of records from the database in batches
B) Retrieves a record chunk as an array
C) Retrieves all records in a collection
D) Splits a collection into smaller collections

Answer: A) Retrieves a chunk of records from the database in batches
Explanation: The chunk() method is used to retrieve records from the database in smaller, manageable batches instead of all records at once.


87. How do you retrieve related models using Eloquent's eager loading?

A) with()
B) load()
C) eagerLoad()
D) include()

Answer: A) with()
Explanation: The with() method is used for eager loading of relationships in Eloquent, which helps to reduce the number of database queries.


88. Which Eloquent method is used to count the number of models in a collection?

A) size()
B) count()
C) total()
D) length()

Answer: B) count()
Explanation: The count() method is used to count the number of models or records in a collection.


89. Which method is used to define the inverse of a hasMany relationship in Eloquent?

A) belongsTo()
B) hasOne()
C) hasMany()
D) morphTo()

Answer: A) belongsTo()
Explanation: The belongsTo() method defines the inverse of a hasMany() relationship. It is used in the related model to refer back to the parent model.


90. What does the increment() method do in Eloquent?

A) Increases the value of a column by a given amount
B) Increases the value of a column and then returns the updated model
C) Decreases the value of a column by a given amount
D) Increases the value of a column and persists the change to the database

Answer: A) Increases the value of a column by a given amount
Explanation: The increment() method is used to increase the value of a specified column by a given amount.


91. What does the decrement() method do in Eloquent?

A) Decreases the value of a column by a given amount
B) Decreases the value of a column and then returns the updated model
C) Increases the value of a column by a given amount
D) Decreases the value of a column and persists the change to the database

Answer: A) Decreases the value of a column by a given amount
Explanation: The decrement() method is used to decrease the value of a specified column by a given amount.


92. How do you retrieve the model with a specific primary key using Eloquent?

A) Model::findOrFail()
B) Model::whereId()
C) Model::retrieve()
D) Model::searchById()

Answer: A) Model::findOrFail()
Explanation: The findOrFail() method retrieves a model by its primary key. If the model is not found, it throws a ModelNotFoundException.


93. How do you define a morphMany relationship in Eloquent?

A) public function comments() { return $this->morphMany('App\Comment', 'commentable'); }
B) public function comments() { return $this->hasMany('App\Comment'); }
C) public function comments() { return $this->morphToMany('App\Comment'); }
D) public function comments() { return $this->morphOne('App\Comment'); }

Answer: A) public function comments() { return $this->morphMany('App\Comment', 'commentable'); }
Explanation: The morphMany() method is used to define a polymorphic one-to-many relationship.


94. What is the default behavior of the delete() method in Eloquent when soft deletes are enabled?

A) Deletes the record permanently
B) Marks the record as deleted without actually removing it from the database
C) Throws an error if you try to delete the record
D) Deletes only the related models

Answer: B) Marks the record as deleted without actually removing it from the database
Explanation: If soft deletes are enabled, the delete() method marks the record as deleted by setting the deleted_at column, but the record is not removed from the database.


95. What method is used to restore a soft-deleted record in Eloquent?

A) restore()
B) revive()
C) undelete()
D) reactivate()

Answer: A) restore()
Explanation: The restore() method is used to restore a soft-deleted record, bringing it back to its original state.


96. How do you retrieve a collection of related models in Eloquent?

A) load()
B) with()
C) retrieve()
D) relatedModels()

Answer: B) with()
Explanation: The with() method is used to eagerly load relationships with the main model, retrieving related models in the same query.


97. What does the whereIn() method do in Eloquent?

A) Filters records based on an array of values
B) Filters records based on a specific condition
C) Filters records based on a column value that is greater than a given value
D) Filters records based on a specific range of dates

Answer: A) Filters records based on an array of values
Explanation: The whereIn() method filters records where a column's value is found in a specified array of values.


98. Which method is used to retrieve the last record in a result set in Eloquent?

A) last()
B) end()
C) getLast()
D) lastOrFail()

Answer: A) last()
Explanation: The last() method retrieves the last record from the result set of an Eloquent query.


99. How do you check if a model exists in the database using Eloquent?

A) exists()
B) hasRecord()
C) findOrFail()
D) isAvailable()

Answer: A) exists()
Explanation: The exists() method checks if the model exists in the database.


100. What method is used to define a one-to-one polymorphic relationship in Eloquent?

A) morphTo()
B) morphOne()
C) hasOne()
D) belongsToMany()

Answer: B) morphOne()
Explanation: The morphOne() method defines a one-to-one polymorphic relationship where a model can belong to multiple other models.


 

Comments

Popular posts from this blog

Lecture Notes Of Day 24: Laravel Policies

MCQs Of Day CRUD 8 Operations with Eloquent