Unit6 - Subjective Questions
INT221 • Practice Questions with Detailed Answers
Define Database Migrations in Laravel. How do the up and down methods function within a migration file?
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 up and down Methods:
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
php
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('flights');
}
Explain the concept of Eloquent ORM. How does it map models to database tables?
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:
php
class 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.
Differentiate between Query Builder and Eloquent ORM with respect to performance and syntax.
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 DB facade. |
Object-Oriented style. Uses Model classes. |
| Return Type | Returns an array or Collection of stdClass objects. |
Returns a Collection of Model instances. |
| Relationships | Requires manual join clauses. |
Handles relationships (OneToMany, ManyToMany) elegantly via methods. |
Example (Select):
- Query Builder:
DB::table('users')->get(); - Eloquent:
User::all();
Describe the process of Seeding in Laravel. How can Model Factories be utilized within seeders?
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/seeders directory.
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.
Write a PHP script to perform CRUD operations (Create, Read, Update, Delete) using Laravel's Query Builder.
Below are the commands to perform CRUD operations using the DB facade (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();
Explain Mass Assignment in Eloquent ORM. What is the role of the guarded properties?
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 guarded, not both.
How can Laravel be configured to use MongoDB? What are the key differences when interacting with MongoDB compared to a SQL database in Laravel?
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.
Discuss the implementation of REST APIs in Laravel. How do API Resources assist in transforming data?
Laravel is widely used to build RESTful APIs. It provides specific routes (routes/api.php) which automatically apply the api middleware 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);
Explain the concept of Soft Deletes in Eloquent ORM. How do you implement and retrieve soft deleted models?
Soft Deletes allow you to "delete" a record without actually removing it from the database. Instead, a deleted_at timestamp 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();.
What are Accessor and Mutator methods in Eloquent models? Provide examples.
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);
}
Describe how to create a One-to-Many relationship using Eloquent ORM. Give an example of a Post and Comment scenario.
A One-to-Many relationship is used when a single model owns any amount of child models. For example, a blog Post may have an infinite number of Comments.
1. The "One" Side (Post)
Define a method (usually plural) in the Post model calling hasMany.
php
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
2. The "Many" Side (Comment)
Define a method (usually singular) in the Comment model calling belongsTo. This table must contain the foreign key (post_id).
php
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
Usage:
To get all comments for a post: $comments = Post::find(1)->comments;
How do you modify an existing database table using Migrations? Explain with an example of adding a new column.
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.
php
public 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');
});
}
- Run Migration:
php artisan migrate.
Explain the significance of HTTP Status Codes when implementing REST APIs in Laravel.
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.
Write the Laravel artisan command to create a Model, Migration, Factory, and Controller simultaneously. Explain the flags used.
Laravel provides a convenient shorthand to generate multiple files associated with a model in a single command.
Command:
php artisan make:model Product -mfc
Or strictly for API:
php artisan make:model Product -mf --api
Explanation 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).
How does Laravel handle database configuration for different environments (Local vs Production)?
Laravel uses the .env file (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 .env file using the env() helper.
Example .env content:
ini
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=secret
Workflow:
- 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.
Explain how to perform a Join operation using Laravel's Query Builder.
The Query Builder provides a join method to combine rows from two or more tables based on a related column between them. This produces a standard SQL INNER JOIN.
Syntax:
$query->join('table_to_join', 'primary_table.column', '=', 'joined_table.column')
Example:
Joining a users table with a contacts table:
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.
What are API Routes in Laravel? How do they differ from Web Routes?
API Routes are defined in routes/api.php, while Web Routes are defined in routes/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.
Define Database Seeding and write the procedure to run a specific seeder class.
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:
Illustrate Aggregates in Query Builder with examples (count, max, min, avg, sum).
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');
Discuss the Active Record Pattern and how Eloquent ORM implements it.
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.