Lecture Notes Of Day 8: CRUD Operations with Eloquent

Lecture Notes Of Day CRUD 

Operations with Eloquent

Objective:

The objective of today’s lesson is to introduce students to CRUD (Create, Read, Update, Delete) operations in Laravel using Eloquent ORM. By the end of this lesson, students should be able to perform all four operations (Create, Read, Update, Delete) on a database table using Laravel’s Eloquent ORM.

Outcome:

  • Students will be able to create new records in the database.
  • Students will be able to retrieve and display records from the database.
  • Students will be able to update existing records.
  • Students will be able to delete records from the database.

Introduction to Eloquent ORM:

Laravel’s Eloquent ORM (Object-Relational Mapping) is a powerful tool for interacting with the database. It provides an active record implementation to work with your database tables as if they were simple PHP objects. Eloquent simplifies the task of managing and querying database records.

In this lesson, we will use Eloquent models to interact with the database and perform CRUD operations. Each model in Laravel corresponds to a database table, and the Eloquent methods allow you to perform database operations easily without writing complex SQL queries.


Step 1: Setting Up the Model

Before diving into the CRUD operations, let's create a simple model that is linked to a table in the database.

For example, let’s say we are working with a User table. The model for this table will be called User. To create this model, run the following command in the terminal:

bash

Copy code

php artisan make:model User

This will create a User.php file in the app/Models directory. By default, the model is linked to a table called users, as Laravel assumes the plural form of the model name as the table name.


Step 2: The CRUD Operations

1. Create (Insert Data into Database)

To insert a new record into the users table, we use the create() method. Before using create(), ensure that the model has been set up to allow mass assignment.

Example:

First, ensure that your model is configured to accept the necessary attributes:

php

Copy code

// In app/Models/User.php

class User extends Model

{

    protected $fillable = ['name', 'email', 'password']; // Mass assignable attributes

}

Now, to create a new user:

php

Copy code

use App\Models\User;

 

$user = User::create([

    'name' => 'John Doe',

    'email' => 'john.doe@example.com',

    'password' => bcrypt('password123'), // Always hash passwords

]);

This code will insert a new record into the users table with the specified attributes.

2. Read (Retrieve Data from Database)

To retrieve data from the database, we use the find(), all(), or where() methods.

Example:

Find a Single Record by ID:

php

Copy code

$user = User::find(1);  // Retrieves the user with ID 1

Retrieve All Records:

php

Copy code

$users = User::all();  // Retrieves all users

Retrieve Records Based on Condition:

php

Copy code

$users = User::where('name', 'John Doe')->get(); // Retrieve users where the name is 'John Doe'

3. Update (Modify Existing Data)

To update an existing record, you can find the record using the find() method, modify its attributes, and then call the save() method.

Example:

php

Copy code

$user = User::find(1); // Find the user with ID 1

$user->name = 'Updated Name'; // Change the name

$user->email = 'updated.email@example.com'; // Update the email

$user->save(); // Save the changes to the database

In this example, we retrieved a user with find(1), modified their name and email, and then saved the updated record back to the database.

4. Delete (Remove Data from Database)

To delete a record, you can use the delete() method after retrieving the record using find() or where().

Example:

php

Copy code

$user = User::find(1);  // Find the user with ID 1

$user->delete();  // Delete the user

Alternatively, you can delete records based on conditions directly:

php

Copy code

User::where('name', 'John Doe')->delete(); // Delete all users named 'John Doe'


Step 3: Practical Example:

Let’s combine all the operations in a single example. Suppose we want to:

1.  Create a new user.

2.  Retrieve and display the user.

3.  Update the user’s name.

4.  Delete the user.

php

Copy code

// Create a new user

$user = User::create([

    'name' => 'Jane Smith',

    'email' => 'jane.smith@example.com',

    'password' => bcrypt('secretpassword'),

]);

 

// Retrieve the user

$retrievedUser = User::find($user->id);

echo "User Name: " . $retrievedUser->name; // Output: Jane Smith

 

// Update the user's name

$retrievedUser->name = 'Jane Updated';

$retrievedUser->save();

 

// Verify the update

$updatedUser = User::find($retrievedUser->id);

echo "Updated User Name: " . $updatedUser->name; // Output: Jane Updated

 

// Delete the user

$updatedUser->delete();


Step 4: Common Pitfalls and Best Practices

  • Mass Assignment: Always make sure that the $fillable or $guarded property is defined in the model to protect against mass-assignment vulnerabilities.
  • Hashing Passwords: Never store plain text passwords. Always use bcrypt() or Hash::make() to hash passwords before storing them.
  • Error Handling: Make sure to handle errors, such as record not found, during CRUD operations. For example, if a find() query does not find a record, it will return null.

Conclusion:

In this lesson, we covered how to perform Create, Read, Update, and Delete operations using Laravel's Eloquent ORM. Eloquent provides a simple and powerful way to interact with your database, allowing you to focus on writing clean and readable code instead of writing raw SQL queries.

By practicing these operations, you can build applications that interact seamlessly with the database, and you’ll be able to manage records effectively.


Homework/Practice:

1.  Create a Post model and implement CRUD operations on a posts table.

2.  Experiment with retrieving records using different query methods (e.g., where(), orWhere(), first(), etc.).

3.  Create a simple form to update user information and delete records.


Recap:

  • Create: User::create()
  • Read: User::find(), User::all(), User::where()
  • Update: Modify attributes and use $user->save()
  • Delete: $user->delete()



Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics