Get Relational Data with Soft Deleted Records in Laravel 11

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

Fetching Relational Data with Soft Deleted Records in Laravel 11

 

Step 1: Set Up Your Models

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;
}

 

Step 2: Seed Your Database

Add some sample data to your database, including soft deleted records.

For example, soft delete a Category record.

$category = Category::find(1);
$category->delete();

 

Step 3: Retrieve Related Data Including Soft Deleted Records

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';
}

 

Step 4: Optional – Only Retrieve Soft Deleted Records

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:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS