Why do you add this check like this?
$query
->whereNotNull('deleted_at') //check if deleted at is null
->withTrashed(); //check if deleted at is null or not null
Do you only want trashed?
$query->onlyTrashed()
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello, everyone I have a problem with the result with one of my queries. There is two database tables with schema like bellow
Schema::create('post_xrefs', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('type', 32);
$table->integer('parent')->nullable();
$table->integer('position')->default(0);
$table->string('status', 20)->default('published');
$table->softDeletes();
$table->timestamps();
});
And
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('post_xref_id')->constrained()->onDelete('cascade');
$table->string('locale', 3)->default('bg');
$table->string('title');
$table->text('excerpt')->nullable();
$table->longText('body')->nullable();
$table->string('slug')->unique();
$table->boolean('is_cached')->default(0);
$table->timestamp('cache_expired')->nullable();
$table->softDeletes();
$table->timestamp('published_at')->useCurrent();
$table->timestamps();
});
I have a method for searching which is
public function scopeSearch($query, $search = '', $locale = null, $excluded = 0)
{
/* just for a example */
/* $this->trashed = false; */
/* $this->trashed = true; */
/* ------------------- */
return Post::with('post_xref')
->whereHas('post_xref', function($query) use($excluded) {
$query->where('type', 'news')
->when($this->trashed, function($query) {
$query->whereNotNull('deleted_at')->withTrashed();
})
->when($excluded, function($query) use($excluded) {
$query->where('id', '!=', $excluded);
});
})
->when(mb_strlen($search) >= 2, function($query) use ($search) {
$query->where('posts.title', 'like', '%' . $search . '%');
})
->where('locale', $locale ? $locale : App::currentLocale())
->orderBy($this->sortField, $this->sortDirection);
}
The relation is
public function post_xref()
{
return $this->belongsTo(PostXref::class, 'post_xref_id');
}
When i set $this->trashed = false; and in the the post_xrefs table deleted_at is null, the result is Ok. By Ok i mean the relation of post_xref is not empty, but when i set $this->trashed = true; then post_xref is empty even when in the post_xrefs table there is a record with deleted_at column not null.
How can i make the query so it return always non empty post_xref relation?
Thanks in advance
@HristoMihaylov remember both
Post::with(['postXref' => function($query) {
$query->onlyTrashed();
}])
->whereHas('postXref', function($query) {
$query->onlyTrashed();
})->get()
Please or to participate in this conversation.