Assignments of Day 7 Eloquent ORM Basics
Assignments of Day 7
Eloquent ORM Basics
Assignment 1: Create a Model and Insert Data
Problem:
Create a Product model with the following fields:
- name (string)
- description (text)
- price (decimal)
- created_at and updated_at (timestamps)
Then, insert a new product record into the products table using Eloquent ORM.
Step-by-Step Solution:
1. Create a Product Model:
o Open your terminal and run the following Artisan command to create a Product model:
bash
Copy code
php artisan make:model Product
2. Define the Model:
o Open the newly created Product.php model file located in app/Models/.
o Add the $fillable property to define which fields can be mass-assigned (i.e., which fields can be inserted via the create() method).
php
Copy code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name', 'description', 'price'];
}
3. Create the products Table:
o You need a migration to create the products table. If it doesn't exist already, create a migration with the following command:
bash
Copy code
php artisan make:migration create_products_table
o Open the migration file in database/migrations/ and define the schema:
php
Copy code
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
4. Run the Migration:
o Apply the migration to create the products table in the database:
bash
Copy code
php artisan migrate
5. Insert Data Using create() Method:
o You can now insert a product record into the products table using the create() method in your controller or tinker:
php
Copy code
Product::create([
'name' => 'Laptop',
'description' => 'A high-performance laptop for developers.',
'price' => 1299.99
]);
6. Verify the Data:
o You can verify the insertion by checking the database directly or using tinker to retrieve the product:
bash
Copy code
php artisan tinker
php
Copy code
Product::all(); // This should return the list of products, including the one you just inserted
Assignment 2: Retrieve and Update Data Using Eloquent
Problem:
- Retrieve a product by its ID (e.g., ID = 1).
- Update the product's price to a new value (e.g., change the price to 1499.99).
Step-by-Step Solution:
1. Retrieve Data Using find():
o To retrieve a product by its ID, use the find() method.
php
Copy code
$product = Product::find(1); // Retrieves the product with ID 1
2. Update the Product:
o After retrieving the product, you can modify its attributes and then call save() to persist the changes in the database.
php
Copy code
$product->price = 1499.99;
$product->save(); // Save the changes to the database
3. Verify the Update:
o You can verify the update by retrieving the product again and checking its price.
php
Copy code
$updatedProduct = Product::find(1);
echo $updatedProduct->price; // Should output 1499.99
Assignment 3: Delete a Product Record
Problem:
- Delete a product from the products table by its ID (e.g., ID = 1).
Step-by-Step Solution:
1. Delete a Record Using find() and delete():
o Retrieve the product by its ID using find(), and then call the delete() method to remove the record from the database.
php
Copy code
$product = Product::find(1); // Find the product with ID 1
$product->delete(); // Delete the product from the database
2. Verify the Deletion:
o After deletion, try retrieving the product again to verify that it has been deleted.
php
Copy code
$product = Product::find(1); // This will return null as the product is deleted
Assignment 4: Retrieve Data Using where() and first()
Problem:
- Retrieve the first product where the price is greater than 1000.
Step-by-Step Solution:
1. Using where() to Filter Data:
o The where() method is used to apply conditions to the query. Combine it with first() to retrieve the first matching record.
php
Copy code
$product = Product::where('price', '>', 1000)->first(); // Retrieves the first product with price > 1000
2. Verify the Result:
o If a product exists with a price greater than 1000, it will be returned. You can display its details:
php
Copy code
echo $product->name; // Display the name of the product
Assignment 5: Mass Assignment with create() and update()
Problem:
- Use the create() method to insert multiple products at once.
- Then, update the price of all products that have a price less than 500.
Step-by-Step Solution:
1. Insert Multiple Products Using create():
o First, you will insert multiple products using the create() method. Ensure the model has the $fillable property defined.
php
Copy code
Product::create([
'name' => 'Smartphone',
'description' => 'A powerful smartphone.',
'price' => 499.99
]);
Product::create([
'name' => 'Tablet',
'description' => 'A lightweight tablet for students.',
'price' => 299.99
]);
2. Update Multiple Records Using update():
o After inserting the products, you can use the update() method to modify multiple records at once based on a condition.
php
Copy code
Product::where('price', '<', 500)->update(['price' => 599.99]); // Update all products with price < 500
3. Verify the Update:
o Retrieve the products with prices less than 500 and check that their prices have been updated:
php
Copy code
$products = Product::where('price', '<', 500)->get();
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n"; // Should output the updated price of each product
}
Conclusion:
These assignments help you practice the Eloquent ORM methods for interacting with the database in Laravel. By working through these, you will be able to understand how to create, retrieve, update, and delete data using Eloquent, as well as how to handle mass assignment and apply conditions in queries.
4o mini
You said:
some more
ChatGPT said:
ChatGPT
More Eloquent ORM Assignments with Step-by-Step Solutions
Assignment 6: Using pluck() to Retrieve Specific Columns
Problem:
Retrieve only the name and price of all products from the products table using the pluck() method.
Step-by-Step Solution:
1. Using the pluck() Method:
o The pluck() method is used to retrieve a single column's value (or a set of columns) from a collection of records.
php
Copy code
$products = Product::pluck('name', 'price');
o The first argument is the column you want to retrieve, and the second argument is an optional key for the retrieved data.
2. Display the Results:
o After retrieving the data, you can loop through the result and display the name and price of each product.
php
Copy code
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
Assignment 7: Using orWhere() for Multiple Conditions
Problem:
Retrieve all products where the price is less than 500 or the name contains the word "Laptop".
Step-by-Step Solution:
1. Using orWhere() to Add Multiple Conditions:
o The orWhere() method allows you to add an additional condition that is connected using the OR SQL operator.
php
Copy code
$products = Product::where('price', '<', 500)
->orWhere('name', 'like', '%Laptop%')
->get();
o This will retrieve all products where the price is less than 500, or the name contains the word "Laptop".
2. Display the Results:
o Once the query is executed, loop through the results to display the products:
php
Copy code
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
Assignment 8: Using count() to Count Records
Problem:
Count the total number of products in the products table.
Step-by-Step Solution:
1. Using count() Method:
o The count() method returns the number of records that match a given query. To count all records in the products table:
php
Copy code
$count = Product::count(); // Counts all products
2. Display the Result:
o After counting the records, display the count:
php
Copy code
echo "Total number of products: " . $count;
Assignment 9: Using exists() to Check If a Record Exists
Problem:
Check if a product with the name "Smartphone" exists in the products table.
Step-by-Step Solution:
1. Using exists() Method:
o The exists() method checks if any records exist that match the given condition.
php
Copy code
$exists = Product::where('name', 'Smartphone')->exists();
2. Display the Result:
o If the product exists, you can display a message saying "Product exists"; otherwise, display "Product not found".
php
Copy code
if ($exists) {
echo "Product exists!";
} else {
echo "Product not found!";
}
Assignment 10: Using limit() and offset() for Pagination
Problem:
Retrieve the first 5 products from the products table and display them.
Step-by-Step Solution:
1. Using limit() to Limit the Number of Records:
o The limit() method restricts the number of records returned. Use it to get the first 5 products:
php
Copy code
$products = Product::limit(5)->get();
2. Display the Results:
o Once the query is executed, you can loop through the products and display their details:
php
Copy code
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
Assignment 11: Using orderBy() to Sort Results
Problem:
Retrieve all products sorted by price in descending order.
Step-by-Step Solution:
1. Using orderBy() to Sort the Data:
o The orderBy() method is used to sort the query results based on a given column. Use desc for descending order or asc for ascending order.
php
Copy code
$products = Product::orderBy('price', 'desc')->get();
2. Display the Results:
o After retrieving the sorted products, loop through and display their details:
php
Copy code
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
Assignment 12: Using updateOrInsert() for Conditional Updates or Insertions
Problem:
Check if a product with the name "Smartwatch" exists. If it exists, update its price; otherwise, insert a new product with that name.
Step-by-Step Solution:
1. Using updateOrInsert() Method:
o The updateOrInsert() method allows you to either update an existing record or insert a new one if it doesn't exist.
php
Copy code
Product::updateOrInsert(
['name' => 'Smartwatch'], // Condition to check if product exists
['price' => 199.99] // Data to update or insert
);
o If a product with the name "Smartwatch" exists, it will update the price; if not, it will insert a new record.
2. Verify the Update/Insert:
o You can verify the result by retrieving the product and checking its price:
php
Copy code
$product = Product::where('name', 'Smartwatch')->first();
echo $product->name . ' - ' . $product->price;
Assignment 13: Using pluck() with Multiple Columns
Problem:
Retrieve the name and price of all products in a key-value pair format (name as the key and price as the value).
Step-by-Step Solution:
1. Using pluck() with Multiple Columns:
o You can retrieve multiple columns using pluck(). In this case, you want to retrieve name as the key and price as the value.
php
Copy code
$products = Product::pluck('price', 'name');
2. Display the Results:
o After using pluck(), you can loop through the results and display each product name with its price:
php
Copy code
foreach ($products as $name => $price) {
echo $name . ' - ' . $price . "\n";
}
Assignment 14: Using get() with select() to Choose Specific Columns
Problem:
Retrieve the name and price columns of all products using the select() method.
Step-by-Step Solution:
1. Using select() to Retrieve Specific Columns:
o The select() method allows you to choose specific columns to retrieve.
php
Copy code
$products = Product::select('name', 'price')->get();
2. Display the Results:
o After retrieving the selected columns, you can loop through and display the product name and price:
php
Copy code
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
Assignment 15: Using chunk() to Process Large Datasets
Problem:
If there are too many records in the products table, retrieve them in chunks of 10 records at a time and display the name and price for each chunk.
Step-by-Step Solution:
1. Using chunk() to Retrieve Data in Chunks:
o The chunk() method is useful when dealing with large datasets. It processes the data in smaller chunks, which is more memory-efficient.
php
Copy code
Product::chunk(10, function($products) {
foreach ($products as $product) {
echo $product->name . ' - ' . $product->price . "\n";
}
});
2. Display the Results:
o The data will be processed in chunks of 10 products. For each chunk, the name and price will be displayed.
Conclusion:
These additional assignments provide more hands-on experience with Eloquent ORM in Laravel. By practicing these tasks, students will develop a solid understanding of how to interact with databases using Eloquent methods, handle large datasets efficiently, and apply various filtering, sorting, and updating techniques.
Comments
Post a Comment