Assignments Of Day 8 CRUD Operations with Eloquent
Assignments Of Day 8
CRUD Operations with Eloquent
Assignment 1: Creating and Retrieving Users
Objective:
- Create a User record.
- Retrieve a user by their ID.
- Display the user's name and email.
Steps:
1. Create a new user in the database:
o First, make sure that your User model is set up correctly to accept mass assignment by adding the $fillable property in the model.
php
Copy code
// In app/Models/User.php
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
2. Create a new user via a route or controller:
o In your controller or route, you can create a new user by passing the necessary data to the create() method of the User model.
php
Copy code
// In web.php or UserController.php
use App\Models\User;
// Create a new user
$user = User::create([
'name' => 'Alice Johnson',
'email' => 'alice.johnson@example.com',
'password' => bcrypt('password123'),
]);
3. Retrieve a user by their ID:
o Use the find() method to retrieve the user by their ID.
php
Copy code
// Retrieve the user with ID 1
$user = User::find(1); // Assuming user ID 1 exists
// Display user name and email
echo "Name: " . $user->name . "<br>";
echo "Email: " . $user->email;
4. Test the output:
o If the user is found, you should see the following output:
makefile
Copy code
Name: Alice Johnson
Email: alice.johnson@example.com
Assignment 2: Updating a User’s Information
Objective:
- Find a user by their ID.
- Update their name and email.
- Save the changes to the database.
Steps:
1. Retrieve a user:
o First, use find() to retrieve the user by their ID.
php
Copy code
$user = User::find(1); // Assuming the user with ID 1 exists
2. Modify the user's attributes:
o Once you have the user object, you can modify any of its properties.
php
Copy code
$user->name = 'Updated Name';
$user->email = 'updated.email@example.com';
3. Save the changes:
o Use the save() method to persist the changes back to the database.
php
Copy code
$user->save(); // Save the updated user details
4. Verify the update:
o Retrieve the user again and display the updated details.
php
Copy code
$updatedUser = User::find(1);
echo "Updated Name: " . $updatedUser->name . "<br>";
echo "Updated Email: " . $updatedUser->email;
Expected Output:
yaml
Copy code
Updated Name: Updated Name
Updated Email: updated.email@example.com
Assignment 3: Deleting a User Record
Objective:
- Retrieve a user by their ID.
- Delete that user from the database.
Steps:
1. Retrieve a user:
o Use the find() method to retrieve a user.
php
Copy code
$user = User::find(1); // Assuming the user with ID 1 exists
2. Delete the user:
o Use the delete() method to delete the user from the database.
php
Copy code
$user->delete(); // Delete the user from the database
3. Verify deletion:
o If you attempt to retrieve the user again, you should receive null since the record has been deleted.
php
Copy code
$deletedUser = User::find(1); // This will return null if the user was deleted
if ($deletedUser === null) {
echo "User has been deleted.";
} else {
echo "User is still in the database.";
}
Expected Output:
sql
Copy code
User has been deleted.
Assignment 4: Retrieve Users Based on a Condition
Objective:
- Retrieve all users whose name is 'John Doe'.
- Display their names and emails.
Steps:
1. Use the where() method to filter the users:
o You can use the where() method to retrieve users whose names are 'John Doe'.
php
Copy code
$users = User::where('name', 'John Doe')->get(); // Retrieve all users with the name 'John Doe'
2. Display the results:
o Loop through the retrieved users and display their names and emails.
php
Copy code
foreach ($users as $user) {
echo "Name: " . $user->name . "<br>";
echo "Email: " . $user->email . "<br><br>";
}
Expected Output (if there are users named 'John Doe'):
makefile
Copy code
Name: John Doe
Email: johndoe@example.com
Name: John Doe
Email: john.doe@anotherexample.com
Assignment 5: Update Multiple Records
Objective:
- Update multiple users’ email addresses at once.
- Use the where() method to target users whose names are 'John Doe'.
Steps:
1. Use where() to filter users:
o Retrieve all users whose name is 'John Doe'.
php
Copy code
$users = User::where('name', 'John Doe')->get();
2. Loop through the users and update their email:
o Iterate through the users and update their email address.
php
Copy code
foreach ($users as $user) {
$user->email = 'newemail@example.com'; // Update email
$user->save(); // Save the changes
}
3. Verify the update:
o After updating, retrieve the users again and display their updated email addresses.
php
Copy code
foreach ($users as $user) {
echo "Updated Email: " . $user->email . "<br>";
}
Expected Output (if there are users named 'John Doe'):
graphql
Copy code
Updated Email: newemail@example.com
Updated Email: newemail@example.com
Assignment 6: Using Query Builder for Deletion
Objective:
- Delete users whose names are 'John Doe' using the query builder.
Steps:
1. Use the where() method with the query builder:
o Use the User::where()->delete() chain to delete users whose names are 'John Doe'.
php
Copy code
User::where('name', 'John Doe')->delete(); // Delete all users named 'John Doe'
2. Verify deletion:
o After deletion, retrieve all users and check if any users named 'John Doe' remain.
php
Copy code
$users = User::where('name', 'John Doe')->get();
if ($users->isEmpty()) {
echo "No users named 'John Doe' found.";
} else {
echo "There are still users named 'John Doe'.";
}
Expected Output:
bash
Copy code
No users named 'John Doe' found.
Conclusion:
These assignments will give you a strong foundation in performing basic CRUD operations using Laravel’s Eloquent ORM. Each assignment introduces a new concept, such as mass assignment, querying the database, updating records, and handling deletion.
Assignment 7: Soft Deleting Users
Objective:
- Implement soft deletes to mark a user as deleted without actually removing them from the database.
- Retrieve users who are "soft deleted."
Steps:
1. Enable Soft Deletes in the Model:
o Open the User model and use the SoftDeletes trait to enable soft deletes.
php
Copy code
// In app/Models/User.php
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes; // Enable soft deletes
protected $dates = ['deleted_at']; // Specify the deleted_at field as a date
}
2. Add the deleted_at column to the database:
o If your table doesn't already have the deleted_at column, you can add it via a migration.
Run the migration command:
bash
Copy code
php artisan make:migration add_deleted_at_to_users_table --table=users
Then, add the following line to the migration file:
php
Copy code
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->softDeletes(); // Add the 'deleted_at' column
});
}
Run the migration:
bash
Copy code
php artisan migrate
3. Soft delete a user:
o Use the delete() method to soft delete a user.
php
Copy code
$user = User::find(1);
$user->delete(); // This will mark the user as deleted, not remove from the DB
4. Retrieve soft-deleted users:
o To retrieve soft-deleted users, use the withTrashed() method.
php
Copy code
$deletedUsers = User::withTrashed()->get();
foreach ($deletedUsers as $user) {
echo "User: " . $user->name . " (Deleted: " . $user->deleted_at . ")<br>";
}
5. Restore a soft-deleted user:
o To restore a soft-deleted user, use the restore() method.
php
Copy code
$user = User::withTrashed()->find(1); // Retrieve the soft-deleted user by ID
$user->restore(); // Restore the user
6. Verify the restoration:
o After restoring, display the user’s details.
php
Copy code
$restoredUser = User::find(1);
echo "Restored User: " . $restoredUser->name;
Assignment 8: Using firstOrCreate and updateOrCreate
Objective:
- Use firstOrCreate() to find or create a record.
- Use updateOrCreate() to update an existing record or create a new one.
Steps:
1. Using firstOrCreate() to find or create a user:
o The firstOrCreate() method will check if a user with a specific email exists. If not, it will create one.
php
Copy code
$user = User::firstOrCreate(
['email' => 'newuser@example.com'], // Search condition
['name' => 'New User', 'password' => bcrypt('newpassword')] // Data to create if not found
);
Explanation: If the user with the email newuser@example.com exists, it will return the first matching record. If not, it will create a new user with the specified name and password.
2. Using updateOrCreate() to update or create a user:
o The updateOrCreate() method will look for an existing record and update it. If it doesn’t find one, it will create a new record.
php
Copy code
$user = User::updateOrCreate(
['email' => 'existinguser@example.com'], // Search condition
['name' => 'Updated User', 'password' => bcrypt('updatedpassword')] // Data to update or create
);
Explanation: If a user with the email existinguser@example.com exists, it will update their name and password. If not, a new user will be created with the given data.
Assignment 9: Mass Assignment for Creating Multiple Records
Objective:
- Use mass assignment to create multiple users at once.
Steps:
1. Ensure $fillable property is set up:
o First, ensure that the User model has a $fillable property for mass assignment.
php
Copy code
// In app/Models/User.php
class User extends Model
{
protected $fillable = ['name', 'email', 'password']; // Allow mass assignment
}
2. Create multiple users at once:
o You can use the create() method within a loop or pass an array of data to insert() for bulk insertion.
php
Copy code
// Using a loop with create()
$users = [
['name' => 'User 1', 'email' => 'user1@example.com', 'password' => bcrypt('password1')],
['name' => 'User 2', 'email' => 'user2@example.com', 'password' => bcrypt('password2')],
['name' => 'User 3', 'email' => 'user3@example.com', 'password' => bcrypt('password3')],
];
foreach ($users as $userData) {
User::create($userData); // Insert each user record
}
3. Bulk insert using insert():
o For more efficient bulk insertion, you can use the insert() method, which avoids creating individual Eloquent models.
php
Copy code
User::insert([
['name' => 'User 4', 'email' => 'user4@example.com', 'password' => bcrypt('password4')],
['name' => 'User 5', 'email' => 'user5@example.com', 'password' => bcrypt('password5')],
['name' => 'User 6', 'email' => 'user6@example.com', 'password' => bcrypt('password6')],
]);
Assignment 10: Use pluck() to Retrieve Specific Columns
Objective:
- Use the pluck() method to retrieve a single column of data from the database.
Steps:
1. Retrieve a list of user emails:
o Use pluck() to retrieve all user emails without retrieving other attributes.
php
Copy code
$emails = User::pluck('email');
foreach ($emails as $email) {
echo $email . "<br>";
}
Explanation: The pluck() method returns an array containing the values of the specified column. In this case, we’re retrieving all the emails from the users table.
2. Retrieve multiple columns:
o If you want to retrieve multiple columns, you can pass an array to pluck().
php
Copy code
$userDetails = User::pluck('name', 'email');
foreach ($userDetails as $email => $name) {
echo "Name: $name, Email: $email<br>";
}
Explanation: In this case, pluck() returns an associative array where the keys are the email addresses and the values are the corresponding user names.
Assignment 11: Count Records and Check Existence
Objective:
- Count the number of records in a table.
- Check if a specific user exists.
Steps:
1. Count the total number of users:
o Use the count() method to count the total number of records in the users table.
php
Copy code
$userCount = User::count();
echo "Total users: " . $userCount;
2. Check if a user exists by email:
o Use the exists() method to check if a user exists with a specific condition.
php
Copy code
$exists = User::where('email', 'john.doe@example.com')->exists();
if ($exists) {
echo "User exists!";
} else {
echo "User does not exist!";
}
Assignment 12: Using get() with Pagination
Objective:
- Paginate results to display users in pages.
Steps:
1. Retrieve users with pagination:
o Use the paginate() method to retrieve users and paginate them.
php
Copy code
$users = User::paginate(5); // Paginate users, 5 per page
foreach ($users as $user) {
echo "Name: " . $user->name . "<br>";
}
2. Display pagination links:
o To display pagination links, you can call the links() method in your view.
php
Copy code
echo $users->links();
Explanation: The paginate() method will automatically handle the database query, limiting the results to the specified number of records per page (in this case, 5 users per page). The links() method will generate the necessary pagination controls.
Comments
Post a Comment