Laravel
Beginner
1 min read
Eloquent ORM Basics and Models
Example
<?php
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'title', 'slug', 'body', 'status', 'user_id', 'published_at',
];
protected $casts = [
'published_at' => 'datetime',
'is_featured' => 'boolean',
'meta' => 'array',
];
// Scope for published posts
public function scopePublished($query)
{
return $query->where('status', 'published')
->whereNotNull('published_at');
}
// Accessor: auto-trim title
public function getTitleAttribute(string $value): string
{
return ucfirst(trim($value));
}
// Relationships
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel