Work with your database using Laravel’s elegant ActiveRecord implementation for intuitive object-relational mapping
Eloquent is Laravel’s ActiveRecord implementation that provides a beautiful, simple way to interact with your database. Each database table has a corresponding “Model” that is used to interact with that table.
Here’s the complete User model from a fresh Laravel installation:
app/Models/User.php
namespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;class User extends Authenticatable{ /** @use HasFactory<\Database\Factories\UserFactory> */ use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var list<string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var list<string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; }}
The User model extends Authenticatable instead of the base Model class because it’s used for authentication.
class User extends Model{ public function posts() { return $this->hasMany(Post::class); }}class Post extends Model{ public function user() { return $this->belongsTo(User::class); }}