Getting remote values through relationship in laravel
I have 3 tables: vehicles
, drivers
and vehicle_driver_owners
.
drivers
All registered drivers are listed. The table vehicles
lists all registered vehicles. vehicle_driver_owners
- pivot table. It shows which drivers are acting as owners of a particular vehicle. (A car can have multiple owners and vice versa)
I made the ratio in all three models ( Vehicle
, Driver
and VehicleDriverOwner
)
Here is the vehicle model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Vehicle extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicles';
protected $softDelete = true;
// EACH VEHICLE CAN BELONG TO MANY OWNERS
public function owners(){
return $this->belongsToMany('Driver', 'vehicle_driver_owners', 'vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id');
}
}
Here's the model Driver
class Driver extends Eloquent{
protected $table = 'drivers'
//EACH DRIVER CAN BE OWNER OF MANY VEHICLES
public function vehicleOwner(){
return $this->belongsToMany('Vehicle', 'vehicle_driver_owners', 'vehicle_driver_owners_driver_id', 'vehicle_driver_owners_vehicle_id');
}
}
Here's the VehicleDriverOwner
model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class VehicleDriverOwner extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicle_driver_owners';
protected $fillable = ['vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id'];
protected $softDelete = true;
}
I tried to use softDelete function for laravel. The vehicle has 3 owners and I want to delete one of them. I also want to store this record in the database. So I used the softDelete function. After removing that particular owner, the column of deleted_at
that row in the table vehicle_driver_owners
was filled with the date.
But now I am trying to view vehicle owners using Vehicle::find(5)->owners
. It shows that the remote owner is also
source to share
Add whereNull ('vehicle_driver_owners.deleted_at') to function owners in Vehicle
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Vehicle extends Eloquent {
use SoftDeletingTrait;
protected $table = 'vehicles';
protected $softDelete = true;
// EACH VEHICLE CAN BELONG TO MANY OWNERS
public function owners(){
return $this->belongsToMany('Driver', 'vehicle_driver_owners', 'vehicle_driver_owners_vehicle_id', 'vehicle_driver_owners_driver_id')
->whereNull('vehicle_driver_owners.deleted_at');
}
}
source to share