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

Ask a Doctor Online: A Simple Guide to Virtual Healthcare

In our fast-paced world, the traditional trip to a doctor’s office isn’t always the most practical first step when health concerns arise. Whether you are dealing with…

Read More

Best Free Programming Ebooks to Learn Software Development

Learning modern technology can feel overwhelming when tutorials are scattered across dozens of websites. Many software developers, engineering students, and IT professionals struggle to find comprehensive study…

Read More

FinOps Training: Understanding Cost Visibility and Optimization

Introduction Moving workloads to the cloud can simplify infrastructure management, but it can also introduce a new financial challenge. Teams can provision resources whenever they need them,…

Read More

The Architecture of Intelligent DataOps: From Ingestion to Automation

Introduction Modern organizations run on distributed data ecosystems. On any given day, an enterprise environment ingests, transforms, and serves petabytes of records sourced from transactional databases, external…

Read More

Transforming Data Reliability: How DataOps Platforms Drive Proactive Monitoring

Introduction Traditional monitoring focuses almost entirely on infrastructure availability and binary job execution states—whether a server is up or whether a task completed. However, modern distributed environments…

Read More

Navigating Pipeline Risks with Expert DevSecOps Consulting Services

Software delivery moves faster today than at any point in technological history. High-performing engineering organizations push code changes to production multiple times a day using automated deployment…

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