Christhofer Natalius
Christhofer Natalius

Reputation: 3388

Laravel eager loading withTrashed

So I have this line OpportunityController@index().

public function index()
{
    $opportunities = Opportunity::with([
        'customer',
        'province',
        'createdBy',
        'closedBy',
        'status',
        'checkedLists',
    ])->paginate();

    return new ApiCollection($opportunities);
}

All of those related models are using SoftDeletes trait. I found out that if those model has been soft-deleted, they will become null, and you need to call withTrashed(). So this is working.

public function index()
{
    $opportunities = Opportunity::with([
        'customer' => function ($query) {
            return $query->withTrashed();
        },
        'status' => function ($query) {
            return $query->withTrashed();
        },
        'province' => function ($query) {
            return $query->withTrashed();
        },
        'createdBy' => function ($query) {
            return $query->withTrashed();
        },
        'closedBy' => function ($query) {
            return $query->withTrashed();
        },
        'checkedLists',
    ])->paginate();

    return new ApiCollection($opportunities);
}

But is there a better (shorter / recommended) way to do this, instead of declaring the function repeatedly like this?

I tried Opportunity::withTrashed([...])->paginate() and Opportunity::with([...])->withTrashed()->paginate, both doesn't work and still return null.

Upvotes: 1

Views: 778

Answers (1)

zahid hasan emon
zahid hasan emon

Reputation: 6233

You can declare it when you are building your relationship.

public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id')->withTrashed();
    }

Upvotes: 4

Related Questions