CLOSE

Eloquent ORM (Object-Relational Mapping) is an advanced feature of the Laravel framework that simplifies database interactions by abstracting database tables into object-oriented models. It provides an expressive and fluent interface for working with database records, allowing developers to interact with database tables using PHP objects and methods rather than writing raw SQL queries.

Defining Models

  • Eloquent models represents database tables. Each model class typically corresponds to a single database table.
  • Models extend the Illuminate\Database\Eloquent\Model class provided by Laravel.

Mapping Table Structure

  • Eloquent models use conventions to map between model attributes and database table columns. For example, a model attribute named name maps to a database column named name by default.
  • You can define custom mappings using Eloquent's $table and $fillable properties.

Model Class Naming:

  • By default convention, the snake case, plural name of the class will be used as the table name unless another name is explicitly specified. For example, the Post model is associated with the posts table.
  • You can override this by specifying the table name in the model using the $table property.

For example: Let our model class name is Post.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    // ...
}

So, in this case, Eloquent will assume the Post model stores records in the posts table, well if your model class name is BlogPost then it assumes the model would store records in an blog_posts table.

  • If your model's corresponding database table does not fit this convention, you may manually specify the mode's table name by defining a table property on the model:
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_posts';
}

Here, I explicitly told Model to map with the table my_posts.

Model Attribute-Column Mapping:

  • Eloquent assumes that the model's attributes match the columns in the associated table. For example, an attribute $name in the model corresponds to a name column in the database table.

Primary Keys

  • Eloquent will assume that each model's corresponding database table has primary key column named id. You can customize this by setting the $primarykey property in the model.
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Flight extends Model
{
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'post_id';
}

Timestamps:

  • By default, Eloquent assumes that your table has created_at and updated_at columns for tracking creation and modification timestamps. If your table doesn't follow this convention, you can disable automatic timestamp management by setting the $timestamps property to false in the model.
class Product extends Model
{
    public $timestamps = false;
}

Customizing Column Names:

  • If your model attributes don't directly map to column names in the table, you can define a custom mapping using the $fillable or $guarded properties. The $fillable property specifies which attributes can be mass-assigned, while the $guarded property specifies which attributes cannot be mass-assigned.
  • The $fillable property specifies which attributes can be mass-assigned If not defined, all attributes are mass-assignable.
  • The $guarded property specifies which attributes are not mass-assignable. If not defined, no attributes are guarded.
class Product extends Model
{
    protected $fillable = ['name', 'price'];
}

// Or

class MyModel extends Model
{
    protected $fillable = ['name', 'email'];
    // OR
    protected $guarded = ['id'];
}

Retrieving Records

  • Eloquent provides various method for querying records, such as all(), find(), where(), first(), get(), etc.
  • Query results are returned as Eloquent model instances or collections, making it easy to work with the retrieved data.

Retrieving All Records:

To retrieve all records from a table, you can use the all() method:

$users = User::all();

Retrieving Single Record by Primary Key:

To retrieve a single record by its primary key, you can use the find() method:

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

Retrieving Single Record by Column Value:

To retrieve a single record based on a column value, you can use the where() method:

$user = User::where('email', 'example@example.com')->first();

Retrieving Multiple Records by Columns Value:

To retrieve multiple records based on a column value, you can use the where() method:

$users = User::where('status', 'active')->get();

Retrieving Records Using Conditions:

You can chain conditions using the where() method for more complex queries:

$users = User::where('role', 'admin')->where('status', 'active')->get();

Retrieving Records with Pagination:

To paginate the results and retrieve a subset of records, you can use the paginate() method:

$users = User::paginate(10); // Paginates records with 10 records per page

Retrieve Only Specific Columns:

Use the select() method to retrieve only specific columns:

$names = User::select('name')->get();

Ordering Results:

Use the orderBy() method to order the results:

$names = User::select('name')->get();

Using Raw Expressions:

Use raw SQL expressions for more complex queries:

$users = User::whereRaw('age > 18')->get();

Creating Records

To create a new records, you can instantiate a new instance of the model class and set its attributes, then call the save() method:

$user = new User();
$user->name = 'Array Singh';
$user->email = 'singh@example.com';
$user->save();

you can also use the create() method, which accepts an array of attributes and creates a new record:

User::create([
    'name' => 'Array Singh',
    'email' => 'singh@example.com'
]);
  • Eloquent models provide methods like create(), update(), save(), delete(), etc., for performing CRUD operations.

Updating Records

To Update an existing record, retrieve the record using method like find() or where(), then update its attributes and call the save() method:

$user = User::find(1);
$user->name = 'Updated Name';
$user->save();

Alternatively, you can use the update() method to update one or more records matching the specified conditions:

User::where('role', 'admin')->update(['status' => 'inactive']);

Deleting Records

To delete an existing record, retrieve the record and call the delete() method:

$user = User::find(1);
$user->delete();

You can also delete records based on conditions using the where() method:

User::where('role', 'guest')->delete();

Soft Deleting Records

Laravel provides support for soft deletes, where records are marked as delete instead of being physically removed from the database. To enable soft deletes, add the Illuminate\Database\Eloquent\SoftDeletes trait to your model and define a $dates property:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

With soft deletes enabled, you can use the delete() method as usual, and the record will be marked as deleted instead of being removed from the database:

$user = User::find(1);
$user->delete();

Restoring Soft Deleted Records

Soft-deleted records can be restored using the restore() method:

$user = User::withTrashed()->find(1);
$user->restore();

Relationships

In the context of Laravel's ORM (Object-Relational Mapping), a “relationship” refers to the association or connection between different database tables represented by Eloquent models.  These relationships mirror real-world interactions between entities and are crucial for efficiently querying and managing data in a relationship database system.

Defining Relationships in Models

To establish relationships between models in Laravel, you need to define these relationships within the corresponding model classes.

There are primarily three types of relationship in Laravel ORM:

1 One-to-One Relationship:

In a one-to-one relationship, each record in one database table is associated with exactly one record in another table. For example, a user may have one profile, and a profile belongs to only one user.

// User.php (Model)
public function profile()
{
    return $this->hasOne(Profile::class);
}

Here, Eloquent determines the foreign key of the relationship based on the parent key model name. In this case, the User model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne(Profile::class, 'foreign_key');

Additionally, Eloquent assumes that the foreign key should have a value matching the primary key column of the parent. In other words, Eloquent will look for the value of the user's id column in the userid column of the Profile record. If you would like the relationship to use a primary key value other than id on your model's $primaryKey property, you may pass a third argument to the hasOne method:

return $this->hasOne(Profile::class, 'foreign_key', 'local_key');

Here, foreign_key column serves as the foreign key in the User table that links back to the local_key in the Profile table.

// Profile.php (Model)
public function user()
{
    return $this->belongsTo(User::class);
}

2 One-to-Many Relationship:

In a one-to-many relationship, a single record in one table can be associated with multiple records in another table. For instance, a blog post can have multiple comments, but each comment belongs to only one post.

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

3 Many-to-Many Relationship:

In a many-to-many relationship, multiple records in one table can be associated with multiple records in another table. An example is the relationship between users and roles. A user can have multiple roles, and a role can belong to multiple users.

// User.php (Model)
public function roles()
{
    return $this->belongsToMany(Role::class);
}
// Role.php (Model)
public function users()
{
    return $this->belongsToMany(User::class);
}