Eloquent permits you to declare database tables in the form of models and lets you have an organized method of accessing
2.Defining an Eloquent Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model{
protected $table = 'posts';
protected $primaryKey = 'post_id';
protected $fillable = ['title', 'content'];
}
4. Interacting with the Database (Crud)
Once the model is defined, you can perform database operations like Create, Read, Update, and Delete (CRUD) directly using the model.
Create:
$post = new Post();
$post->title = 'First Post';
$post->content = 'This is the content of the first post.';
$post->save();
Or using create() (with $fillable defined):
php
Post::create([
'title' => 'Second Post',
'content' => 'This is the content of the second post.',
]);
Get the first record:
$post = Post::where('title', 'First Post')->first();
$post = Post::find(1);
$title = 'Updated Title';
$post->title = $title;
$post->save();
Using query builder methods:
Post::where('id', 1)->update(['title' => 'Another Updated Title']);
Delete data from the table:
$post = Post::find(1);
$post->delete();
Post::destroy(1); // Delete by primary key
Post::where('title', 'First Post')->delete();
5. Fluent Relationships
return $this->hasMany(Comment::class);
}
public function roles()
{return $this->belongsToMany(Role::class);
}
Polymorphic Relationships:
public function imageable(){
return $this->morphTo();
}
Using Relationships:
$post = Post::find(1);
$comments = $post->comments;
Scopes allow you to encapsulate common query logic in the model.
Defining a Local Scope:
public function scopePublished($query){
return $query->where('is_published', true);
}
Using the Scope:
$publishedPosts = Post::published()->get();
protected static function booted(){
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
Transform attributes when accessing or setting them.
Accessor:
Transform a field when retrieving it:
public function getTitleAttribute($value){
return ucfirst($value);
}
Mutator:
Transform a field when setting it:
public function setTitleAttribute($value){
$this->attributes['title'] = strtolower($value);
}
8. Eloquent Events
Eloquent supports lifecycle events to hook into model actions:
creating, created
updating, updated
deleting, deleted
protected static function booted(){
static::creating(function ($post) {
$post->slug = Str::slug($post->title);
});
}
Eager loading minimizes database queries when accessing relationships.
Without Eager Loading (N+1 problem):
$posts = Post::all();
foreach ($posts as $post) {
echo $post->comments; // Queries each post for comments
}
10. Advanced Features
Use $fillable or $guarded to define which fields can be mass-assigned.
protected $fillable = ['title', 'content'];
Custom Timestamps:
11.Override default timestamps:
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';
such tables. (Crud System)
Eloquent permits you to declare database tables in the form of models and lets you have
an organized method of accessing such tables.Each model in Eloquent will represent
a database table and each instance of the model will represent one row in the table.
2.Defining an Eloquent Model
Eloquent by default presumes that the table name is plural to the name of the model. In this case, the User model corresponds to the users table.
3.Model
3.Model
To generate a model using Artisan use the following command in the terminal:
php artisan make:model Post
The generated model is in the directory app/Models.
php artisan make:model Post
The generated model is in the directory app/Models.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model{
protected $table = 'posts';
protected $primaryKey = 'post_id';
protected $fillable = ['title', 'content'];
}
4. Interacting with the Database (Crud)
Once the model is defined, you can perform database operations like Create, Read, Update, and Delete (CRUD) directly using the model.
Create:
$post = new Post();
$post->title = 'First Post';
$post->content = 'This is the content of the first post.';
$post->save();
Or using create() (with $fillable defined):
php
Post::create([
'title' => 'Second Post',
'content' => 'This is the content of the second post.',
]);
Retrieve all records from the table:
$posts = Post::all();
$post = Post::find(1); // Fetch row with id = 1
$posts = Post::where('title', 'like', '%First%')->get();
$post = Post::find(1); // Fetch row with id = 1
$posts = Post::where('title', 'like', '%First%')->get();
Get the first record:
$post = Post::where('title', 'First Post')->first();
$post = Post::find(1);
$title = 'Updated Title';
$post->title = $title;
$post->save();
Using query builder methods:
Post::where('id', 1)->update(['title' => 'Another Updated Title']);
Delete data from the table:
$post = Post::find(1);
$post->delete();
Post::destroy(1); // Delete by primary key
Post::where('title', 'First Post')->delete();
5. Fluent Relationships
Fluent provides an easy way to define relationships between tables.
Types of Relationships:
One-to-One:
public function user(){
return $this->hasOne(User::class);
}
public function user(){
return $this->hasOne(User::class);
}
One-to-Many:
public function comments(){return $this->hasMany(Comment::class);
}
Many-to-Many:
public function roles()
{return $this->belongsToMany(Role::class);
}
Polymorphic Relationships:
public function imageable(){
return $this->morphTo();
}
Using Relationships:
$post = Post::find(1);
$comments = $post->comments;
6. Fluent Scopes
Scopes allow you to encapsulate common query logic in the model.
Defining a Local Scope:
public function scopePublished($query){
return $query->where('is_published', true);
}
Using the Scope:
$publishedPosts = Post::published()->get();
Global Scope:
Apply a scope to every query for the model:
protected static function booted(){
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('is_published', true);
});
}
7. Accessors and Mutators
Transform attributes when accessing or setting them.
Accessor:
Transform a field when retrieving it:
public function getTitleAttribute($value){
return ucfirst($value);
}
Mutator:
Transform a field when setting it:
public function setTitleAttribute($value){
$this->attributes['title'] = strtolower($value);
}
8. Eloquent Events
Eloquent supports lifecycle events to hook into model actions:
creating, created
updating, updated
deleting, deleted
protected static function booted(){
static::creating(function ($post) {
$post->slug = Str::slug($post->title);
});
}
9. Eager Loading
Eager loading minimizes database queries when accessing relationships.
Without Eager Loading (N+1 problem):
$posts = Post::all();
foreach ($posts as $post) {
echo $post->comments; // Queries each post for comments
}
With Eager Loading:
$posts = Post::with('comments')->get();
foreach ($posts as $post) {
echo $post->comments; // No additional queries
}
$posts = Post::with('comments')->get();
foreach ($posts as $post) {
echo $post->comments; // No additional queries
}
10. Advanced Features
Soft Deletes:
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model{
use SoftDeletes;
}
class Post extends Model{
use SoftDeletes;
}
Mass Assignment Protection:
Use $fillable or $guarded to define which fields can be mass-assigned.
protected $fillable = ['title', 'content'];
Custom Timestamps:
11.Override default timestamps:
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';
12. Advantages of Using Eloquent
Simplicity: Simple syntax for database operations.
Relationships: Easy handling of complex relationships.
Query Efficiency: Eager loading and scopes.
Extensibility: Accessors, Mutators, and Events make it highly extensible.view more about laravel
Relationships: Easy handling of complex relationships.
Query Efficiency: Eager loading and scopes.
Extensibility: Accessors, Mutators, and Events make it highly extensible.view more about laravel
Post a Comment