Write Eloquent models with relationships and scopes
✓Works with OpenClaudeYou are a Laravel backend developer. The user wants to write Eloquent models with relationships and scopes that handle complex data retrieval and filtering patterns.
What to check first
- Run
php artisan tinkerto verify Eloquent is available and models load correctly - Check your database migrations exist by running
php artisan migrate:status - Verify the database connection in
.envfile matches your setup
Steps
- Create a new model with
php artisan make:model Post -mto generate both model and migration file - Define table name explicitly in the model if it doesn't follow Laravel's plural convention using
protected $table = 'custom_posts' - Create relationships in the model using methods like
hasMany(),belongsTo(), orbelongsToMany()with return type declarations - Define query scopes as public methods prefixed with
scope(e.g.,scopeActive()) that acceptBuilder $queryas first parameter - Use scope chaining in queries with
->active()->recent()->get()to combine multiple scopes - Add fillable or guarded properties to enable mass assignment:
protected $fillable = ['title', 'content', 'user_id'] - Cast attributes using
$castsarray for type safety:'published_at' => 'datetime' - Test relationships with
php artisan tinkerusingPost::with('author', 'comments')->first()
Code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
protected $fillable = ['title', 'content', 'user_id', 'published_at'];
protected $casts = [
'published_at' => 'datetime',
'is_featured' => 'boolean',
];
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
public function scopeActive(Builder $query): Builder
{
return $query->whereNotNull('published_at')
->where('published_at', '<=', now());
}
public function scopeRecent(Builder $query): Builder
{
return $query->orderBy('published_at', 'desc');
}
public function scopeByAuthor(Builder $query, User $user): Builder
{
return $query->where('user_id', $user->id);
}
public function scopeFeatured(Builder $query): Builder
{
return $query->where('is_featured
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Laravel Skills
Other Claude Code skills in the same category — free to download.
Laravel Setup
Scaffold Laravel project with authentication and API
Laravel Migration
Create database migrations with foreign keys and indexes
Laravel API Resource
Build REST API with resources and form requests
Laravel Queue
Set up job queues with Redis/database drivers
Laravel Testing
Write feature and unit tests with PHPUnit and Pest
Laravel Livewire
Build reactive components with Laravel Livewire
Laravel Nova
Customize Laravel Nova admin panels
Want a Laravel skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.