Using Eloquent ORM for Database Interaction and CRUD Operations

Eloquent is a powerful Object-Relational Mapping (ORM) integrated into Laravel. It provides an easy and convenient way to interact with the database and perform CRUD operations (Create, Read, Update, Delete). Here is a guide on using Eloquent ORM in Laravel:

 

Define the Model

First, you need to define a model that maps to a table in the database. For example, if you have a "users" table, you can create a "User" model using the Artisan command:

php artisan make:model User

 

Interact with Data

You can use methods in the model to interact with the data.

  • Create a new record:
    $user = new User;
    $user->name = 'John Doe';
    $user->email = '[email protected]';
    $user->save();
    ​
  • Retrieve all records:
    $users = User::all();
  • Retrieve a record based on the primary key:
    $user = User::find($id);​
  • Update a record:
    $user = User::find($id);
    $user->name = 'Jane Doe';
    $user->save();
  • Delete a record:
    $user = User::find($id);
    $user->delete();
    

 

Model Relationships

Eloquent allows you to define relationships between models. You can define relationships such as "belongsTo", "hasMany", "hasOne", etc. to interact with data through associations. This enables you to easily query and manage relationships between tables in the database.

 

Query Customization

Eloquent provides a range of methods to customize queries and filter data. You can use methods like where, orderBy, groupBy, etc. to perform complex queries and retrieve data based on your requirements.

 

Using Eloquent ORM in Laravel allows you to interact with the database easily and efficiently. It reduces the need to write raw SQL queries and provides convenient methods for working with data.