LARAVEL LARAVEL Eloquent ORM & Database 2 — Questions and Answers
Question 1: Which Artisan command creates a new Eloquent model along with its migration file?
- php artisan make:model Post -m (Correct answer)
- php artisan make:model Post --migrate
- php artisan create:model Post
- php artisan model:make Post -m
Correct answer: php artisan make:model Post -m
The -m flag with make:model instructs Artisan to generate a corresponding database migration file simultaneously.
Question 2: What does the `$hidden` property do in a Laravel Eloquent model?
- Excludes listed attributes from array and JSON serialization (Correct answer)
- Prevents attributes from being stored in the database
- Hides columns from query results
- Marks fields as encrypted at rest
Correct answer: Excludes listed attributes from array and JSON serialization
Attributes listed in $hidden are omitted when the model is converted to an array or JSON, commonly used for passwords and tokens.
Question 3: How does Laravel's `updateOrCreate()` method work?
- It updates an existing record if found by the given attributes, otherwise creates a new one (Correct answer)
- It updates all records matching a condition
- It creates a record only if no records exist in the table
- It deletes and recreates a record with new values
Correct answer: It updates an existing record if found by the given attributes, otherwise creates a new one
updateOrCreate() performs an upsert: it searches by the first argument's attributes and updates with the second, or creates if not found.
Question 4: What is a database migration in Laravel?
- A version-controlled PHP file that defines database schema changes (Correct answer)
- A backup of the current database state
- An ORM mapping between models and tables
- A configuration file for database credentials
Correct answer: A version-controlled PHP file that defines database schema changes
Migrations are PHP classes that describe schema changes (create tables, add columns) in a version-controlled, reversible manner.
Question 5: Which method do you call to roll back the most recent batch of database migrations?
- php artisan migrate:rollback (Correct answer)
- php artisan migrate:undo
- php artisan migrate:down
- php artisan migrate:revert
Correct answer: php artisan migrate:rollback
php artisan migrate:rollback reverses the last batch of migrations by calling the down() method on each migration file in reverse order.
Question 6: What is the purpose of Eloquent's `withTrashed()` method?
- To include soft-deleted records in a query result (Correct answer)
- To permanently delete all soft-deleted records
- To restore soft-deleted records
- To disable soft delete for a query
Correct answer: To include soft-deleted records in a query result
withTrashed() modifies the query scope to include records where deleted_at is not null, making soft-deleted rows visible.
Which Artisan command creates a new Eloquent model along with its migration file?