Laravel Eloquent Relationship withTrashed() Method With Example

Introduction

In this blog post, we will explore the powerful withTrashed() method in Laravel’s Eloquent ORM. This method allows us to retrieve related models, including soft deleted records. We will dive into the details of how to use this method and provide a live use example to demonstrate its functionality.

What is the withTrashed() Method?

The withTrashed() method is a convenient feature provided by Laravel’s Eloquent ORM. It allows us to fetch related models along with any soft deleted records. By default, when using relationships in Laravel, soft deleted records are excluded. However, there are cases where we may want to include them in our queries. That’s where the withTrashed() method comes in handy.

How to Use the withTrashed() Method

To use the withTrashed() method, we need to define a relationship between two models in our Laravel application. Let’s take a look at an example to understand this better.

Suppose we have two models: User and Post. Each user can have multiple posts. We have set up a one-to-many relationship between these two models using Eloquent ORM.

In our User model, we define the relationship as follows:

<?php

   

namespace App\Models;

  

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\SoftDeletes;

  

class User extends Authenticatable

{

    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

  

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function posts()

    {

        return $this->hasMany(Post::class);

    }

}

Now, let’s say we want to retrieve all posts of a user, including any soft deleted posts. We can do this by calling the withTrashed() method on the relationship.

$user = User::find(1);
$posts = $user->posts()->withTrashed()->get();

This will return a collection of posts, including any soft deleted posts associated with the user.

Example

Now that we understand how the withTrashed() method works, let’s see a live use example to illustrate its functionality.

Suppose we have an application where users can write blog posts. Each post can have multiple comments. We have set up a one-to-many relationship between the Post and Comment models.

In our Post model, we define the relationship as follows:

<?php

    

namespace App\Models;

    

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

    

class comment extends Model

{

    use HasFactory, SoftDeletes;

  

    /**

     * Write code on Method

     *

     * @return response()

     */

    protected $fillable = [

        'title', 'body', 'slug'

    ];

  

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function comments()

    {

        return $this->belongsTo(Comment::class);

    }

}

Let’s say we want to retrieve all comments of a post, including any soft deleted comments. We can achieve this by calling the withTrashed() method on the relationship.

$post = Post::find(1);
$comments = $post->comments()->withTrashed()->get();

This will give us a collection of comments, including any soft deleted comments associated with the post.

I hope it can help you…

Related Posts

Elevating DevSecOps and SRE Efficiency with a Software Delivery Governance Platform

Introduction Enterprise software engineering has reached a tipping point where systemic complexity threatens structural delivery stability. Modern engineering organizations routinely support highly fragmented ecosystems populated by hundreds…

Read More

Best Hospitals in India for International Patients and Affordable Surgery Costs

Introduction Global healthcare costs are rising rapidly, forcing many families to look for alternative solutions when facing serious medical diagnoses. In countries like the United States, the…

Read More

A Beginner Guide to Data Analytics Automation using Enterprise DataOps Workflows

Organizations rely heavily on fast, accurate, and reliable business intelligence to make critical commercial decisions. Whether it is predicting customer churn or managing real-time inventory levels, business…

Read More

Integrating AI Tools in DataOps Pipelines: A Comprehensive Guide

Introduction Modern organizations deal with a massive influx of data from applications, IoT devices, and cloud services. Managing these data volumes requires speed, accuracy, and agility. Traditional…

Read More

Modern Cloud DataOps Platforms for Reliable Data Pipelines

Introduction Modern organizations depend heavily on data. Every department, from finance and sales to healthcare, manufacturing, marketing, and customer support, needs reliable data to make better decisions….

Read More

Advanced DataOps Monitoring Tools for Enterprises: A Comprehensive Implementation Guide

Introduction Enterprise data environments are becoming more complex as organizations depend on cloud platforms, data lakes, data warehouses, real-time pipelines, analytics tools, and automated workflows. When one…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x