Models
Eloquent ORM
Eloquent is Laravel's ORM for working with database records as PHP objects. Each model represents a table, and each instance represents a row.
// Good
class User extends Model
{
// properties and methods
}
// Bad
class user extends Model
{
// properties and methods
}
- Always extend the base
Modelclass. - Use singular, PascalCase names for models (e.g.,
User,Invoice). - Place models in the
app/Modelsdirectory.
Naming Conventions
Model names should be singular and use PascalCase. Table names should be plural (Laravel does this automatically).
// Good
class User extends Model
{
// properties and methods
}
// Bad
class user_table extends Model
{
// properties and methods
}
Relationships
Define relationships using Eloquent's built-in methods. Use plural method names for relationships that return collections.
// Good
public function posts()
{
return $this->hasMany(Post::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
public function roles() {
return $this->belongsToMany(Role::class);
}
// Bad
public function get_posts()
{
return $this->hasMany(Post::class);
}
public function getProfile()
{
return $this->hasOne(Profile::class);
}
- Use
hasMany,hasOne,belongsTo, andbelongsToManyfor relationships. - Document relationships with PHPDoc for clarity.
Scopes
Use local scopes for reusable query logic. Scope methods should start with scope and use camelCase.
// Good
public function scopeActive($query)
{
return $query->where('active', 1);
}
public function scopeOfType($query, $type)
{
return $query->where('type', $type);
}
// Bad
public function getActiveUsers($query)
{
return $query->where('active', 1);
}
- Call scopes as
$users = User::active()->get();
Best Practices
- Use mass assignment protection (
$fillableor$guarded). - Use accessors and mutators for attribute transformation.
- Use casting for automatic type conversion.
- Avoid business logic in models; use service classes for complex operations.
- Use soft deletes for models that should not be permanently removed.
Example: Comprehensive Model
/**
* User model representing application users.
*/
class User extends Model
{
use SoftDeletes;
protected $fillable = ['name', 'email', 'password'];
public function casts()
{
return [
]
}
/**
* Get the user's posts.
*/
public function posts()
{
return $this->hasMany(Post::class);
}
/**
* Scope for active users.
*/
public function scopeActive($query)
{
return $query->where('active', 1);
}
/**
* Accessor for full name.
*/
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
}