In this article, I’ll guide you through retrieving related data along with soft deleted records in Laravel 11. By default, Laravel's relationships exclude soft deleted data when querying related models. However, there are situations where you might need to include soft deleted records in the relationship. Don’t worry; Laravel provides simple solutions to handle this scenario.
Fetching Relational Data with Soft Deleted Records in Laravel 11
Make sure your models are set up with the SoftDeletes
trait. This allows soft deleting and querying soft deleted data.
For Product
and Category
models:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
public function category()
{
return $this->belongsTo(Category::class);
}
}
class Category extends Model
{
use SoftDeletes;
}
Add some sample data to your database, including soft deleted records.
For example, soft delete a Category
record.
$category = Category::find(1);
$category->delete();
To include soft deleted records in your relationship queries, use the withTrashed()
method in your query.
Example:
Fetch Products
along with their Category
, including soft deleted categories:
$products = Product::with(['category' => function ($query) {
$query->withTrashed();
}])->get();
foreach ($products as $product) {
echo $product->name . ' belongs to ' . $product->category->name ?? 'No category';
}
If you only want to fetch related data that is soft deleted, you can use the onlyTrashed()
method.
$products = Product::with(['category' => function ($query) {
$query->onlyTrashed();
}])->get();
You might also like: