Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bmcn99's avatar

Unable to retrieve trashed relationship information using ->withTrashed()

I have orders, which are linked to meals. I normally retrieve these orders using:

$this->orders()->with('meals')->get()

After I try soft deleting a meal however, I tried to get it using the following:

$this->orders()->with('meals')->withTrashed()->get()//Did not work

$this->orders()->with('meals')->get() // And changed the meals function to read 
public function meals(){

        return $this->hasMany(Meal::class)->withTrashed();

    }
//This also did not work

Everything I'm reading says this is the correct way to do it but the listed meal relation is always null. I checked the database and the meals table has the deleted_at column like it should. If I set that back to null, undeleting the item the relationship is restored and I am able to retrieve it.

What am I doing wrong here? How can I properly access this deleted relationship?

Edit: I should say I am encountering this problem on the order history page because I still want to show that they ordered it in the past. I am currently wrestling with not showing active orders that have their meals deleted, I think I need to add ->whereNull('meals.deleted_at') or something to my orders query, but that's a problem for another post.

0 likes
5 replies
jlrdw's avatar
$orders = Orders::findOrFail($id);  // or just find

$orders->meals()->withTrashed()->get(); 

Something like that, adjust per your relations.

bmcn99's avatar

This gives me information about the meal for a single order directly, but I don't know that I can incorporate this into my current code/use it at all.

This is what I am doing currently:

$orders = $this->orders()->with('meals')->with('owner')->where('orders.ordered_for', '>=', $start)->get();

Which has the deleted meals coming back as null: https://imgur.com/hBeJODI

If I alter that to

$this->orders()->with('meals')->withTrashed()->with('owner')->where('orders.ordered_for', '>=', $start)->get()

I get 'Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withTrashed()'

And of course if I try

$this->orders()->meals()->withTrashed()->with('owner')->where('orders.ordered_for', '>=', $start)->get()

Which is trying to do something else entirely from what I want I get the expected error:

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::meals()

EDIT: I should say this is inside my user model, and so $this refers to the current User.

bmcn99's avatar

That worked great, thank you!

ardf16's avatar

How about whereHas ? It doesnt seem to work like this.

Please or to participate in this conversation.