How to use the Eloquent ORM for database queries



Image not found!!

Eloquent is the Object-Relational Mapping (ORM) system included with the Laravel PHP framework. It provides an elegant and expressive way to interact with your database by allowing you to work with database tables using object-oriented syntax. Below are some common operations and examples of how to use Eloquent for database queries in Laravel.

1. Model Creation:

Create a model using Artisan command:

php artisan make:model YourModel

2. Basic CRUD Operations:

Create (Insert):

// Create a new instance of the model
$record = new YourModel;

// Set the attributes
$record->column1 = 'value1';
$record->column2 = 'value2';

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

Read (Select):

Get All Records:
$records = YourModel::all();
Get a Single Record by ID:
$record = YourModel::find($id);
Get Records with Conditions:
$records = YourModel::where('column', 'value')->get();

Update:

// Find the record by ID
$record = YourModel::find($id);

// Update the attributes
$record->column1 = 'new_value1';
$record->column2 = 'new_value2';

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


Delete:

// Find the record by ID
$record = YourModel::find($id);

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

3. Mass Assignment:

When creating or updating records, you can use mass assignment to set multiple attributes at once:

// Create a new record
$record = YourModel::create([
    'column1' => 'value1',
    'column2' => 'value2',
]);

// Update a record
YourModel::where('id', $id)->update([
    'column1' => 'new_value1',
    'column2' => 'new_value2',
]);

4. Relationships:

Eloquent supports defining relationships between models. For example, if you have a Post model and a Comment model,
you can define a relationship between them:

// Post Model
class Post extends Model {
    public function comments() {
        return $this->hasMany(Comment::class);
    }
}

// Comment Model
class Comment extends Model {
    // ...
}

// Access comments for a post
$post = Post::find($postId);
$comments = $post->comments;



These are just some basic examples, and Eloquent provides many other features for complex queries, eager loading, and more. Refer to the Laravel documentation for a comprehensive guide: Eloquent ORM - Laravel Documentation.



=== Happy Coding :)