LARAVEL

Introduction to Eloquent Models


Eloquent ORM (Object-Relational Mapping) is Laravel's built-in ActiveRecord implementation, providing a simple and expressive way to interact with your database. Eloquent allows you to work with database tables using PHP objects and provides an intuitive syntax for querying, inserting, updating, and deleting records.

 

Introduction to Eloquent Models:

Eloquent models serve as the bridge between your PHP code and database tables. Each Eloquent model represents a single database table, and each instance of the model corresponds to a row in that table.

 

Creating Eloquent Models:

To create an Eloquent model, you typically create a new PHP class that extends Laravel's Illuminate\Database\Eloquent\Model class. Here's an example of a basic Eloquent model for a User table:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Model properties and methods
}
ActiveRecord

 

Defining Table Relationships:

Eloquent makes it easy to define relationships between different database tables. You can define relationships like one-to-one, one-to-many, many-to-many, etc., using Eloquent's methods such as hasOne, hasMany, belongsTo, belongsToMany, etc.

Example:

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

 

Performing CRUD Operations:

Eloquent provides expressive methods for performing CRUD (Create, Read, Update, Delete) operations on your database tables.

 

  • Create: You can create a new record using the create() method:
$user = User::create(['name' => 'John Doe', 'email' => 'john@example.com']);

 

  • Read: You can retrieve records from the database using methods like all(), find(), where(), etc.
$users = User::all();
$user = User::find(1);
$users = User::where('age', '>', 18)->get();

 

  • Update: You can update existing records using the update() method:
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

 

  • Delete: You can delete records using the delete() method:
$user = User::find(1);
$user->delete();

 

Querying with Eloquent:

Eloquent provides a fluent query builder interface that allows you to construct complex database queries using a readable syntax.

$users = User::where('age', '>', 18)
             ->orderBy('created_at', 'desc')
             ->get();

 


LARAVEL