Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent withtrashed() for soft deletes on eager loading query - Laravel 5.1

I'm trying to use withTrashed() with eager loading. I've created a new _withtrashed function in my model, but the query comes back with a NULL for my client

Client model:

// Client
public function client()
{
    return $this->belongsTo('App\Client');
}

// Client (withtrashed for soft deletes)
public function client_withtrashed()
{
    return $this->belongsTo('App\Client')->withTrashed();
}

Order controller:

/**
 * Show order.
 */
public function show($id)
{
    $order = Order::with('client_withtrashed')    ---> it works normally with: Order::with('client') , except I don't get the soft deleted rows
            ->where('id', '=', $id)
            ->firstOrFail();

dd($order); displays an empty client

#relations: array:1 [
   "client_withtrashed" => null 

Any ideas? I decided on the solution above because I couldn't get withTrashed() to work with my eager query $order = Order::with('client_withtrashed')->withTrashed()

like image 794
user3489502 Avatar asked Nov 24 '15 17:11

user3489502


1 Answers

Well you can't define that on a relationship, but you can add constraints when you are eager loading:

$order = Order::with(['client' => function ($query) {
        $query->withTrashed();
    }])
    ->where('id', '=', $id)
    ->firstOrFail();

You can check the eager loading constraints in the docs

EDIT:

You can define withTrashed() on your relationship, just make sure that your models are using the SoftDeleteTrait.

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Client extends Eloquent {
    use SoftDeletingTrait;

}
like image 176
Fabio Antunes Avatar answered Sep 20 '22 23:09

Fabio Antunes