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

DataOps Integration Tools: A Guide to Seamless Data Pipeline Integration

Modern enterprise organizations generate vast quantities of information across dozens of isolated systems. Managing this distributed ecosystem requires engineering infrastructure that can ingest, process, and deliver data…

Read More

Transforming Global Healthcare Solutions with Expert Treatment Guidance

Introduction As healthcare networks expand globally, an increasing number of individuals look beyond their geographic borders for solutions. However, exploring foreign medical environments presents its own set…

Read More

Affordable Healthcare Secrets: How MyHospitalNow Helps Patients Find Verified Hospitals and Save Money

Introduction The single greatest hurdle in modern healthcare is the lack of transparent, centralized data. Comparing treatment costs across different institutions is notoriously difficult. A procedure that…

Read More

DataOps Security in Pipelines: Best Practices for Data Engineers

Data has become the primary asset of the modern enterprise, but it is also the most vulnerable. As organizations migrate from static data warehouses to distributed, real-time…

Read More

Evaluating Enterprise DataOps Tools for Secure Automation and Pipeline Orchestration

Introduction Enterprise data systems are expanding at an unprecedented rate. Organizations no longer manage just a few centralized databases. Instead, modern infrastructure spans across hybrid cloud environments,…

Read More

Comprehensive Guide to Evaluating Open Source DataOps Observability Tools

Introduction Modern data ecosystems are experiencing an unprecedented surge in complexity. Organizations no longer rely on a single, isolated relational database to power their business intelligence. Today’s…

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