Laravel Eloquent Relationship withTrashed() Method Example

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

This post is focused on laravel eloquent relationship withTrashed(). you will learn laravel eloquent relationship with trashed. I explained simply about laravel eloquent delete relationships. I explained simply about laravel relationship withTrashed.

The `withTrashed()` method in Laravel allows you to retrieve related models, including soft-deleted models, in a relationship query. To explain it step by step, let's consider an example where we have two models: `User` and `Post`.

1. First, define the relationships between the models. In the `User` model, you might have a `hasMany()` relationship with the `Post` model:

app/Models/User.php

<?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);

}

}

2. In the `Post` model, you can define a `belongsTo()` relationship with `User`, Also Now, let's assume that you implemented SoftDeletes trait in the `Post` model. You need to import the trait at the top of the file:

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model

{

use HasFactory, SoftDeletes;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'title', 'body', 'slug'

];

/**

* Write code on Method

*

* @return response()

*/

public function user()

{

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

}

}

3. To retrieve all posts for a user, including the soft-deleted ones, use the `withTrashed()` method in the relationship query. For example:

$user = User::find(1);

$posts = $user->posts()->withTrashed()->get();

In this example, the `$posts` collection will contain all the related posts for the user, including the soft-deleted ones.

4. You can also use the `withTrashed()` method on the inverse relationship. For example, to retrieve the user for a specific post, including soft-deleted users, you can do:

$post = Post::find(1);

$user = $post->user()->withTrashed()->first();

Now, the `$user` object will have the related user, even if it has been soft-deleted.

Note: Soft-deletion allows you to "softly" delete a record from the database by marking it as deleted without actually removing it. This is useful when you want to retain the record's data for historical purposes or have the option to restore it later.

I hope it can help you...

Tags :
Shares