1
votes

I have a 2 models, vehicles and manufacturer. and Manufacturer has one to many relationship with the vehicles. I have enabled soft deletion on both the models. I have an html table of all the vehicles, that shows title, slug, manufacturer_id and deleted_at (laravel default) fields in the html table.

Now when i soft delete a vehicle from its page, everything works fine and it shows all vehicles + soft deleted ones. Similarly if i delete the manufacturer of that vehicle, i still see all the manufacturers + soft deleted manufacturers. Now problem occurs when i go back to the vehicles page, i get an error saying

Trying to get property of non-object 

Which means that its looking for the manufacturer_id which doesn't exist any more. Here is my eloquent query to get all vehicles

// Vehicle Controller
/* This query basically gets all fields in the first column from vehicle model
   and all the fields in the second column from manufacturer model*/

   $this->vehicle->getAllWithTrash( 
       ['id', 'title', 'description', 'is_active', 'manufacturer_id', 'created_at', 'updated_at', 'deleted_at'],
       ['title', 'id'] 
   ) );


// Eloquent Repository
   public function getAllWithTrash( $columns1 = array('*'), $columns2 = array('*') ){

        return Vehicle::withTrashed()->with(['manufacturer' => function($q) use ($columns2){
                $q->select($columns2);
        }])->get($columns1)->toJson();

    }

So i want to modify this query, so it fetches all the vehicles + soft deleted ones with all the manufacturers whether they are soft deleted or not.

1

1 Answers

6
votes

see the withTrashed() function

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to appear in a result set using the withTrashed method on the query:

$flights = App\Flight::withTrashed()->where('account_id', 1)->get();

The withTrashed method may also be used on a relationship query:

$flight->history()->withTrashed()->get();

try this:

// Eloquent Repository
   public function getAllWithTrash( $columns1 = array('*'), $columns2 = array('*') ){

        return Vehicle::withTrashed()->with(['manufacturer' => function($q) use ($columns2){
                $q->withTrashed()->select($columns2);
        }])->get($columns1)->toJson();

    }