You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

1. Double-check your model's SoftDeletes setup

First off, make sure you've done both required steps for SoftDeletes in Laravel 5.3:

  • You're correctly importing and using the SoftDeletes trait.
  • You've added deleted_at to your model's $dates property. 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.

2. Watch your query builder order

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();
3. Verify relationship usage

If you're using these methods on related models, make sure:

  • The related model also uses the SoftDeletes trait 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();
4. Check for conflicting global scopes

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.

5. Clear cached caches

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:23:27