CodexBloom - Programming Q&A Platform

Data inconsistency when using Eloquent ORM's soft deletes in Laravel 9 with relation queries

👀 Views: 757 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-27
laravel eloquent soft-deletes php

After trying multiple solutions online, I still can't figure this out. I've looked through the documentation and I'm still confused about This might be a silly question, but I'm experiencing an scenario with Eloquent ORM's soft deletes in Laravel 9. I have a `User` model that uses soft deletes, and I also have a `Post` model that belongs to the `User`. When I try to fetch a user along with their posts, I notice that the soft-deleted users are included in the results, which leads to data inconsistency in my application. Here's my `User` model: ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model { use SoftDeletes; protected $fillable = ['name', 'email']; public function posts() { return $this->hasMany(Post::class); } } ``` And my `Post` model: ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = ['title', 'body', 'user_id']; public function user() { return $this->belongsTo(User::class); } } ``` When I run the following query to get the user with their posts: ```php $user = User::with('posts')->find($userId); ``` I expect to only get active users along with their posts, but it's including soft-deleted users as well. I tried using the `onlyTrashed()` method on the relationship like this: ```php $user = User::with(['posts' => function ($query) { $query->onlyTrashed(); }])->find($userId); ``` However, this doesn't solve my question, as it still returns the soft-deleted users. I want to ensure that no soft-deleted users are included in the query results at all. I've already checked the documentation and searched for similar issues but haven't found a clear solution. Can anyone guide to understand how to achieve this without modifying the default behavior of Eloquent? For context: I'm using Php on Windows. I'd really appreciate any guidance on this. I'm working on a application that needs to handle this. What am I doing wrong? Is this even possible? This is part of a larger microservice I'm building. What would be the recommended way to handle this?