withTrashed not being applied to relation tables

  eloquent, laravel, relation

I am running into this issue where I can’t retrieve the softdeleted data of the relation tables. My approach was to use the withTrashed method, but it gave me no luck whatsoever.

This is the line of code:

return response()->json($user->orders()->withTrashed()->with('order_details', 'order_details.product', 'address')->get());

It like ignores what’s inside the with clause. How do I fix this issue? Any help would be appreciated, many thanks!

EDIT

My Order model:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use IlluminateNotificationsNotifiable;
use IlluminateDatabaseEloquentConcernsHasEvents;

class Order extends Model
{
    use HasFactory, SoftDeletes, Notifiable, HasEvents;

    protected $fillable = [
        'user_id', 'address_id', 'total_price', 'order_status', 'is_delivered'
    ];

    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function product() {
        return $this->belongsTo(Product::class);
    }

    public function address() {
        return $this->belongsTo(Address::class, 'address_id');
    }
    public function order_details() {
        return $this->hasMany(OrderDetails::class, 'order_id', 'id');
    }
}

My user model:

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentSoftDeletes;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function orders() {
        return $this->hasMany(Order::class);
    }
}

Source: Laravel

Leave a Reply