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

How DataOps and MLOps Work Together for Scalable AI Pipelines

Introduction In the current landscape of artificial intelligence, building a model is only the beginning. The real challenge for enterprise teams lies in the transition from a…

Read More

Evaluating Modern DataOps Tools Across Business Analytics Infrastructure

Introduction Managing data pipelines used to be a straightforward task for single analytics teams. Today, data ecosystems are complex, fast-moving, and frequently fragmented across multiple cloud environments….

Read More

Essential Guide To Choosing And Mastering Modern Enterprise DataOps Platforms

Introduction DataOps platforms represent the modern standard for orchestrating the entire data lifecycle, from initial ingestion to final analytics delivery. By applying agile engineering and automated DevOps…

Read More

Exploring Financial Operations Workflows in Modern Cloud Environments

Introduction The Certified FinOps Professional is the definitive benchmark for experts looking to master the intersection of finance, engineering, and business. As organizations transition from traditional data…

Read More

Strategic Certified FinOps Engineer integrates governance with cloud operations

Introduction The shift to cloud computing has fundamentally altered how businesses manage infrastructure, but it has also introduced significant financial complexities that many engineering teams struggle to…

Read More

Certified FinOps Manager Knowledge for Cloud Financial Governance

Introduction The shift toward cloud-native infrastructure has brought undeniable speed, but it has also introduced significant financial complexity. The Certified FinOps Manager is a professional designation designed…

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