Laravel 5.3调用withTrashed()报错:未定义方法,已引入SoftDeletes trait
Hey there, let's break down why you're hitting issues with onlyTrashed() and withTrashed() even after setting up SoftDeletes in Laravel 5.3. Here are the most common culprits to check:
First off, make sure you've done both required steps for SoftDeletes in Laravel 5.3:
- You're correctly importing and using the
SoftDeletestrait. - You've added
deleted_atto your model's$datesproperty. Laravel 5.3 doesn't auto-include this field in date parsing, so skipping this will break all soft delete scope methods.
Example of a properly configured model:
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; // This line is critical for Laravel 5.3 protected $dates = ['deleted_at']; }
Also verify your database table has a deleted_at timestamp field that allows null values—if the field is missing or has the wrong type, these methods will throw errors.
In Laravel 5.3, soft delete scope methods like withTrashed() or onlyTrashed() need to be called before adding other query constraints. If you chain them after where() or other clauses, you might run into unexpected errors due to how the query builder applies scopes.
❌ Wrong order:
$trashedPosts = Post::where('category_id', 1)->onlyTrashed()->get();
✅ Correct order:
$trashedPosts = Post::onlyTrashed()->where('category_id', 1)->get();
If you're using these methods on related models, make sure:
- The related model also uses the
SoftDeletestrait and has the proper setup. - You're calling the soft delete method on the relationship query, not the parent model.
Example of correct usage for relationships:
// Get trashed posts belonging to a specific user $user = User::find(1); $trashedPosts = $user->posts()->onlyTrashed()->get();
If you've added custom global scopes to your model, they might be overriding or conflicting with the SoftDeletes built-in scope. For example, a global scope that forces a where('deleted_at', null) condition will negate withTrashed() calls.
Try temporarily removing your custom global scopes to test—if the methods start working, you'll need to adjust your scope logic to respect soft delete states.
Sometimes Laravel's auto-load or configuration caches can prevent model changes from taking effect. Run these commands to clear everything:
php artisan clear-compiled php artisan cache:clear php artisan config:clear
内容的提问来源于stack exchange,提问作者leoalmar

