Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use withTrashed when I'm querying using eager loading?

Tags:

laravel

I have some tables, one of which is a table named Users where there are soft deleted rows.

I have code like:

$appointments = Appointment::with('user')->get();

$return = array();
foreach ($appointments as $key => $appointment) {
    $return[] = array(
        $appointment->customer_name,
        $appointment->date->format('d/m/Y'),
        $appointment->time,
        $appointment->status,
        $appointment->user->full_name,
    );
}

Because the row with the user is deleted, I get an error on the line with:

$appointment->user->full_name

because of course there is no match for this user.

I tried adding withTrashed() to the first line, both before and after with('user') but this didn't help.

How do I ensure that this query really does return all appointments with all users, even deleted ones?

like image 735
Rich Bradshaw Avatar asked Feb 24 '14 18:02

Rich Bradshaw


1 Answers

withTrashed() can be applied to the query that retrieves the users like so:

$appointments = Appointment::with(array('user' => function($query) {
    $query->withTrashed();
}))->get();

You can also apply withTrashed() to both the appointment and their users:

$appointments = Appointment::with(array('user' => function($query) {
    $query->withTrashed();
}))->withTrashed()->get();

Alternatively, you can add withTrashed() to the association method to apply it whenever the association is loaded:

public function user() {
  return $this->hasOne('User')->withTrashed();
}
like image 103
TonyArra Avatar answered Nov 11 '22 11:11

TonyArra