Unit 6 subjective questions Getting started with databases
INT221 — Mvc Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define Database Migrations in Laravel. How do the
upanddownmethods function within a migration file?Model answer
Database Migrations are like version control for your database, allowing the team to modify and share the application's database schema. They are typically paired with Laravel's Schema Builder to easily build the application's database schema.
The
upanddownMethods:A migration class contains two primary methods:
-
up()Method:- Used to add new tables, columns, or indexes to the database.
- This runs when you execute the command
php artisan migrate. - Example: Creating a 'flights' table.
-
down()Method:- Used to reverse the operations performed by the
upmethod. - This runs when you execute the command
php artisan migrate:rollback. - Example: Dropping the 'flights' table.
- Used to reverse the operations performed by the
PHPpublic function up() { Schema::create('flights', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('flights'); } -
-
Question 2 of 20
Explain the concept of Eloquent ORM. How does it map models to database tables?
Model answer
Eloquent ORM (Object-Relational Mapper) is Laravel's native ActiveRecord implementation. It provides a simple, beautiful mechanism for working with the database. Each database table has a corresponding "Model" that is used to interact with that table.
Mapping Models to Tables:
-
Naming Convention: By default, Eloquent assumes that the table name is the plural, snake_case form of the Model class name.
- Model:
FlightTable:flights - Model:
UserDetailTable:user_details
- Model:
-
Overriding the Table: If the table does not follow the convention, it can be manually specified in the model:
PHPclass Flight extends Model { // Explicitly defining the table name protected $table = 'my_flights'; }- Primary Keys: Eloquent assumes each table has a primary key column named
id. This can also be overridden using the$primaryKeyproperty.
-
-
Question 3 of 20
Differentiate between Query Builder and Eloquent ORM with respect to performance and syntax.
Model answer
Query Builder vs Eloquent ORM
Feature Query Builder Eloquent ORM Definition A fluent interface for creating and running database queries directly. An implementation of the ActiveRecord pattern, working with Objects (Models). Performance Generally faster as it is a direct wrapper around PDO and has less overhead. Slightly slower due to the overhead of creating model instances and managing relationships. Syntax Procedural style. Uses the DBfacade.Object-Oriented style. Uses Model classes. Return Type Returns an arrayorCollectionofstdClassobjects.Returns a CollectionofModelinstances.Relationships Requires manual joinclauses.Handles relationships (OneToMany, ManyToMany) elegantly via methods. Example (Select):
- Query Builder:
DB::table('users')->get(); - Eloquent:
User::all();
- Query Builder:
-
Question 4 of 20
Describe the process of Seeding in Laravel. How can Model Factories be utilized within seeders?
Model answer
Seeding is the process of populating the database with test or initial data. Laravel includes the ability to seed the database using seed classes stored in the
database/seedersdirectory.Using Model Factories:
Instead of manually specifying data for every row, Model Factories allow you to define a blueprint for your database records using libraries like Faker to generate dummy data.
Steps:
- Define a Factory: Create a factory using
php artisan make:factory UserFactory. - Define State: In the
definition()method, return an array of default column values. - Call in Seeder: Use the factory inside the
runmethod ofDatabaseSeeder.
PHP// In DatabaseSeeder.php public function run() { // Create 50 fake users \App\Models\User::factory(50)->create(); }This approach allows developers to quickly generate thousands of rows of realistic test data for development.
- Define a Factory: Create a factory using
-
Question 5 of 20
Write a PHP script to perform CRUD operations (Create, Read, Update, Delete) using Laravel's Query Builder.
Model answer
Below are the commands to perform CRUD operations using the
DBfacade (Query Builder).1. Create (Insert)
php
use Illuminate\Support\Facades\DB;DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
'votes' => 0
]);2. Read (Select)
php
// Get all rows
$users = DB::table('users')->get();// Get specific row with where clause
$user = DB::table('users')->where('name', 'John Doe')->first();3. Update
php
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);4. Delete
php
DB::table('users')->where('votes', '<', 100)->delete(); -
-
Question 6 of 20
Explain Mass Assignment in Eloquent ORM. What is the role of the
$fillableand$guardedproperties?Model answer
Mass Assignment occurs when you send an array of data to the model creation method to create a new record in a single line, e.g.,
User::create(Input::all()).Security Vulnerability:
Without protection, a malicious user could inject parameters into the HTTP request (like
is_admin = 1) that you didn't intend to allow them to modify.Protection Properties:
To prevent this, Eloquent requires you to whitelist or blacklist attributes.
-
$fillable(Whitelist):- Specifies which attributes are allowed to be mass assigned.
- php
protected $fillable = ['name', 'email', 'password'];
-
$guarded(Blacklist):- Specifies which attributes are NOT allowed to be mass assigned. All others will be allowed.
- php
protected $guarded = ['id', 'is_admin'];
Note: You should use either
$fillableor$guarded, not both. -
-
Question 7 of 20
How can Laravel be configured to use MongoDB? What are the key differences when interacting with MongoDB compared to a SQL database in Laravel?
Model answer
Laravel does not support MongoDB out of the box, but it is easily integrated using packages like
jenssegers/laravel-mongodb.Configuration Steps:
- Install Package:
composer require jenssegers/mongodb. - Configure Database: Add the MongoDB connection details in
config/database.php(host, port 27017, database name). - Extend Model: Eloquent models must extend
Jenssegers\Mongodb\Eloquent\Modelinstead of the defaultIlluminate\Database\Eloquent\Model.
Key Differences:
- Schema-less: MongoDB doesn't require migrations to define columns strictly, though migrations can still be used for indexes.
- Primary Keys: MongoDB uses
_id(ObjectId) as the primary key instead of an auto-incrementing integerid. - Relationships: While the syntax looks similar (e.g.,
hasMany), MongoDB embeds or references documents (NoSQL structure) rather than using strict foreign key constraints like SQL.
- Install Package:
-
Question 8 of 20
Discuss the implementation of REST APIs in Laravel. How do API Resources assist in transforming data?
Model answer
Laravel is widely used to build RESTful APIs. It provides specific routes (
routes/api.php) which automatically apply theapimiddleware group (stateless, typically utilizing tokens).Key Components:
- Routes: Defined using standard HTTP verbs:
GET(retrieve),POST(create),PUT/PATCH(update),DELETE(remove). - Controllers: Handle the business logic and return JSON responses using
response()->json($data, 200).
API Resources (Transformation):
When building an API, you often need a transformation layer between your Eloquent models and the JSON response returned to users (e.g., to hide specific fields like passwords or ids, or to format dates).
-
Creating a Resource:
php artisan make:resource UserResource. -
Transformation Logic: Inside the
toArraymethod of the resource:
php
public function toArray($request)
{
return [
'id' => $this->id,
'full_name' => this->last_name,
'email' => $this->email,
];
} -
Usage:
return new UserResource($user);
- Routes: Defined using standard HTTP verbs:
-
Question 9 of 20
Explain the concept of Soft Deletes in Eloquent ORM. How do you implement and retrieve soft deleted models?
Model answer
Soft Deletes allow you to "delete" a record without actually removing it from the database. Instead, a
deleted_attimestamp is set on the record. If this column is not null, the record is considered deleted by Eloquent queries.Implementation:
- Migration: Add the column using
$table->softDeletes();in the migration file. -
Model: Use the
SoftDeletestrait in the Model class.
php
use Illuminate\Database\Eloquent\SoftDeletes;class Post extends Model {
use SoftDeletes;
}
Operations:
- Delete:
$post->delete();(Setsdeleted_attimestamp). - Retrieve (Normal):
Post::all();(Excludes soft deleted). - Retrieve (Include Deleted):
Post::withTrashed()->get();. - Restore:
$post->restore();.
- Migration: Add the column using
-
Question 10 of 20
What are Accessor and Mutator methods in Eloquent models? Provide examples.
Model answer
Accessors and Mutators allow you to format Eloquent attribute values when you retrieve them from or insert them into the database.
Accessors (Getters)
Transform data when it is retrieved from the database.
- Naming:
get{AttributeName}Attribute - Example: Capitalizing a first name automatically.
php
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Mutators (Setters)
Transform data before saving it to the database.
- Naming:
set{AttributeName}Attribute - Example: Hashing a password before saving.
php
public function setPasswordAttribute($value)
{
value);
}
- Naming:
-
Question 11 of 20
Describe how to create a One-to-Many relationship using Eloquent ORM. Give an example of a
PostandCommentscenario.Model answer
A One-to-Many relationship is used when a single model owns any amount of child models. For example, a blog
Postmay have an infinite number ofComments.1. The "One" Side (Post)
Define a method (usually plural) in the
Postmodel callinghasMany.PHPclass Post extends Model { public function comments() { return $this->hasMany(Comment::class); } }2. The "Many" Side (Comment)
Define a method (usually singular) in the
Commentmodel callingbelongsTo. This table must contain the foreign key (post_id).PHPclass Comment extends Model { public function post() { return $this->belongsTo(Post::class); } }Usage:
To get all comments for a post:
$comments = Post::find(1)->comments; -
Question 12 of 20
How do you modify an existing database table using Migrations? Explain with an example of adding a new column.
Model answer
To modify an existing table, you do not edit the original migration file (which has already run). Instead, you create a new migration file.
Steps:
-
Create Migration:
php artisan make:migration add_votes_to_users_table --table=users -
Define Changes (Schema
tablemethod):
UseSchema::tableinstead ofSchema::create.
PHPpublic function up() { Schema::table('users', function (Blueprint $table) { // Adding a new integer column $table->integer('votes')->after('email')->default(0); }); } public function down() { Schema::table('users', function (Blueprint $table) { // Reversing the change $table->dropColumn('votes'); }); } 3. **Run Migration:** `php artisan migrate`. -
-
Question 13 of 20
Explain the significance of HTTP Status Codes when implementing REST APIs in Laravel.
Model answer
In REST APIs, HTTP status codes are crucial for indicating the outcome of a request to the client (frontend or external service). Laravel makes it easy to return these codes via the
response()helper.Common Codes:
- 200 OK: Standard response for successful HTTP requests (GET, PUT).
- 201 Created: The request has been fulfilled and resulted in a new resource being created (POST).
- Example:
return response()->json($user, 201);
- Example:
- 204 No Content: The request processed successfully, but there is no content to return (often used for DELETE).
- 400 Bad Request: The server cannot process the request due to client error.
- 401 Unauthorized: Authentication is required and has failed or has not been provided.
- 403 Forbidden: The server understood the request but refuses to authorize it (Permissions).
- 404 Not Found: The requested resource could not be found.
- 422 Unprocessable Entity: Validation errors occurred.
-
Question 14 of 20
Write the Laravel artisan command to create a Model, Migration, Factory, and Controller simultaneously. Explain the flags used.
Model answer
Laravel provides a convenient shorthand to generate multiple files associated with a model in a single command.
Command:
php artisan make:model Product -mfcOr strictly for API:
php artisan make:model Product -mf --apiExplanation of Flags:
make:model Product: Creates the Eloquent model namedProduct.-m(or--migration): Creates a Migration file for creating the database table.-f(or--factory): Creates a Model Factory for seeding dummy data.-c(or--controller): Creates a Controller class.--api: If used with controller generation, it creates an API controller (excludescreateandeditmethods which are for HTML forms).
-
Question 15 of 20
How does Laravel handle database configuration for different environments (Local vs Production)?
Model answer
Laravel uses the
.envfile (Environment Variables) to handle configuration, ensuring sensitive credentials are not hard-coded in the source code.Structure:
The database connection logic is located in
config/database.php, which reads values from the.envfile using theenv()helper.Example
.envcontent:
ini
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=secretWorkflow:
- Local Dev: You set
DB_DATABASE=local_dbin your local.env. - Production: The server has its own
.envfile withDB_DATABASE=prod_dband a strong password. - Laravel automatically loads the variables relevant to the environment where the code is running.
- Local Dev: You set
-
Question 16 of 20
Explain how to perform a Join operation using Laravel's Query Builder.
Model answer
The Query Builder provides a
joinmethod to combine rows from two or more tables based on a related column between them. This produces a standard SQLINNER JOIN.Syntax:
$query->join('table_to_join', 'primary_table.column', '=', 'joined_table.column')Example:
Joining a
userstable with acontactstable:PHP$users = DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.*', 'contacts.phone', 'orders.price') ->get();Other Join Types:
leftJoin(): Left Outer Join.rightJoin(): Right Outer Join.crossJoin(): Cartesian product.
-
Question 17 of 20
What are API Routes in Laravel? How do they differ from Web Routes?
Model answer
API Routes are defined in
routes/api.php, while Web Routes are defined inroutes/web.php. They serve different purposes in the application architecture.API Routes (
routes/api.php):- Middleware: They are assigned the
apimiddleware group. - State: They are stateless. They do not use sessions or cookies. Authentication is usually token-based (e.g., Sanctum or JWT).
- Prefix: Laravel automatically prepends
/apito these routes (e.g.,www.example.com/api/user). - Rate Limiting: Usually have throttle limits applied to prevent abuse.
Web Routes (
routes/web.php):- Middleware: Assigned the
webmiddleware group. - State: Stateful. They manage sessions, cookies, and CSRF protection.
- Purpose: Intended for returning HTML views to a browser.
- Middleware: They are assigned the
-
Question 18 of 20
Define Database Seeding and write the procedure to run a specific seeder class.
Model answer
Database Seeding is the process of filling your database with initial data. This is useful for populating lookup tables (like countries, states) or creating test data for development.
Procedure to Run a Specific Seeder:
-
Create the Seeder:
php artisan make:seeder UsersTableSeeder -
Write Logic:
Edit therun()method in the generated file to insert data (using DB facade or Factories). -
Register (Optional):
Call the seeder from the mainDatabaseSeeder.phpclass using$this->call(UsersTableSeeder::class);. -
Run the Seeder:
- Run all seeders:
php artisan db:seed - Run specific class:
php artisan db:seed --class=UsersTableSeeder - Run during migration:
php artisan migrate:fresh --seed(Rebuilds DB and seeds it).
- Run all seeders:
-
-
Question 19 of 20
Illustrate Aggregates in Query Builder with examples (count, max, min, avg, sum).
Model answer
The Query Builder provides various methods to retrieve aggregate values from database tables without retrieving all records and processing them in PHP (which is inefficient).
Examples:
-
Count: Returns the number of records.
php
$count = DB::table('users')->count(); -
Max: Returns the maximum value of a given column.
php
$price = DB::table('orders')->max('price'); -
Min: Returns the minimum value.
php
$price = DB::table('orders')->min('price'); -
Avg: Returns the average value.
php
$average = DB::table('orders')->avg('price'); -
Sum: Returns the sum of a column.
php
$total = DB::table('orders')->sum('price');
-
-
Question 20 of 20
Discuss the Active Record Pattern and how Eloquent ORM implements it.
Model answer
Active Record is an architectural pattern found in software that stores data in relational databases. It was named by Martin Fowler.
The Pattern Concept:
A row in a database table is wrapped into a class (an object). Thus, an object instance is tied to a single row in the table.
- The Class represents the Table.
- The Object Instance represents a Row.
- Properties of the object represent columns.
Eloquent Implementation:
Laravel's Eloquent ORM is an implementation of Active Record.
-
Interaction: Instead of writing SQL (
INSERT INTO users...), you create a new object and save it.
php
$user = new User;
$user->name = 'John';
$user->save(); // Persists to DB -
Logic: The model class (
User) can contain business logic and relationships specific to that data, encapsulating both data and behavior in one place.
That's unit 6
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 6 of INT221 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 6 of INT221 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.