Lecture Notes of Day 7: Eloquent ORM Basics

 

Lecture Notes of Day 7

Eloquent ORM Basics


Objective:

  • To introduce students to Eloquent ORM for efficient database interactions in Laravel.
  • Students will learn how to use Eloquent to query and manipulate data in a database without writing raw SQL queries.

Outcome:

By the end of this class, students will be able to:

  • Define and create models using php artisan make:model.
  • Use various Eloquent methods like find, save, and create to interact with the database.
  • Understand how Eloquent makes database operations simpler and more intuitive.

Explanation:

1. What is Eloquent ORM?

  • Eloquent is Laravel's default Object-Relational Mapping (ORM) tool that provides an easy-to-use, fluent interface to interact with a database.
  • It allows you to work with database records as objects rather than writing complex SQL queries.

2. Eloquent Model Definition

In Laravel, each database table can be represented by a model. A model is a PHP class that interacts with a corresponding table in the database. Models are used to retrieve, insert, and update data in the database.

Creating a Model with Artisan Command:

  • Laravel provides an Artisan command to create models easily. You can create a model using the following command:

php artisan make:model ModelName

This command will create a model file in the app/Models directory. For example, to create a model for a Post:

php artisan make:model Post

This will generate a file Post.php in the app/Models folder:

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Post extends Model

{

    // The Eloquent model for interacting with the 'posts' table

}

  • Important: By default, Laravel assumes the model corresponds to a table with the plural form of the model name (e.g., Post model corresponds to the posts table).
  • If you want to specify a different table name, you can define it in the model:

php

Copy code

class Post extends Model

{

    protected $table = 'my_custom_table';

}

3. Common Eloquent Methods

a. Retrieving Data:

Eloquent provides several methods for retrieving data from the database.

  • all(): Retrieves all records from the table.

php

Copy code

$posts = Post::all();

  • find(): Retrieves a record by its primary key.

php

Copy code

$post = Post::find(1);  // Finds a post with id = 1

  • where(): Retrieve records with a specific condition.

php

Copy code

$posts = Post::where('status', 'published')->get();

  • first(): Retrieves the first record that matches a condition.

php

Copy code

$post = Post::where('status', 'published')->first();

b. Inserting Data (Create and Save):

Eloquent allows inserting new data into the database using create() or save() methods.

  • create(): Inserts a new record into the database. This method requires that you define the $fillable property in the model to protect against mass-assignment vulnerabilities:

php

Copy code

class Post extends Model

{

    protected $fillable = ['title', 'content', 'status'];

}

Now, to insert a new post:

php

Copy code

Post::create([

    'title' => 'My New Post',

    'content' => 'This is the content of my new post.',

    'status' => 'published'

]);

  • save(): You can also create an object instance and then call the save() method to insert it into the database:

php

Copy code

$post = new Post;

$post->title = 'Another Post';

$post->content = 'Content goes here...';

$post->status = 'draft';

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

c. Updating Data:

Eloquent makes updating records easy using the update() method.

  • You can retrieve a record, modify its properties, and then call save() to update it:

php

Copy code

$post = Post::find(1);

$post->title = 'Updated Title';

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

Alternatively, you can use the update() method on a query:

php

Copy code

Post::where('id', 1)->update(['status' => 'published']);

d. Deleting Data:

You can delete a record using the delete() method.

  • Delete by ID:

php

Copy code

$post = Post::find(1);

$post->delete();

  • Delete using conditions:

php

Copy code

Post::where('status', 'draft')->delete();

4. Additional Eloquent Features

  • Timestamps: Eloquent automatically maintains created_at and updated_at columns in your database (you can disable this feature if not needed).

php

Copy code

class Post extends Model

{

    public $timestamps = false;  // Disable automatic timestamps

}

  • Relationships: Eloquent makes it easy to define relationships between models like one-to-many, many-to-many, etc.
    • Example: A Post has many Comments, so you would define a method comments() in the Post model.

php

Copy code

public function comments()

{

    return $this->hasMany(Comment::class);

}

  • Mass Assignment Protection: As shown earlier, use $fillable or $guarded to protect against mass-assignment vulnerabilities.

5. Recap and Hands-on Practice

  • Recap: We’ve covered how to define models, and use methods like find(), create(), save(), and delete() to interact with the database.
  • Practice:

1.  Create a Product model with fields like name, description, and price.

2.  Write code to insert a new product into the products table.

3.  Retrieve a product by its ID and update its details.

4.  Delete a product by its ID.


Conclusion:

In this class, you’ve learned the basics of Eloquent ORM and how to use it to interact with your database in Laravel. Instead of writing raw SQL queries, Eloquent allows you to write clean, expressive, and easy-to-maintain code to handle database operations.



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