Shashika
Shashika

Reputation: 1636

Remove one to one relationship in Laravel

I'm using Laravel 5.2 and I have created a one to one relation as follows.

 $driver    = Driver::find($driver->id);
 $vehicle = Vehicle::find($vehicleId);
 $vehicle->driver()->associate($driver);
 $vehicle->save();

This works perfectly. In some scenarios I need to break this relationship by removing the particular driver from the vehicle.

$driver    = Driver::find($driver->id);
$vehicle = Vehicle::find($vehicleId);
$vehicle->driver_id->NULL;
$vehicle->save();

But this doesn't work. I have tried some other approaches.

$vehicle->driver()->delete();

$vehicle->driver()->dissociate();

Following are the two models.

class Driver extends Model
{
    public function vehicle()
    {
        return $this->hasOne(Vehicle::class);
    }
}

class Vehicle extends Model
{
    protected $primaryKey = 'vehicle_number';
    public $incrementing = false;

    public function driver()
    {
        return $this->belongsTo(Driver::class);
    }
}

Nothing is working in my case. Could anyone please give a hint, what's wrong in there.

Upvotes: 3

Views: 3422

Answers (4)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41320

To remove a parent model from a child model, you may use the dissociate method. This method will set the relationship's foreign key to null:

$vehicle->driver()->dissociate();
$vehicle->save();

Upvotes: 0

KuKeC
KuKeC

Reputation: 4610

First of all i think you did wrong with inserting data

$driver  = Driver::find($driver->id);
$vehicle = Vehicle::find($vehicleId);
$vehicle->driver()->associate($vehicle);
$vehicle->save();

should be

$driver  = Driver::find($driver->id);
$vehicle = Vehicle::find($vehicleId);
$vehicle->driver()->associate($driver);
$vehicle->save();

Your models should be like below

class Driver extends Model
{
    public function vehicle()
    {
        return $this->belongsTo(Vehicle::class);
    }
}

class Vehicle extends Model
{
    protected $primaryKey = 'vehicle_number';
    public $incrementing = false;

    public function driver()
    {
        return $this->hasOne(Driver::class);
    }
}

Try it and let me know if it helped you

Upvotes: 2

Cliffon Dmello
Cliffon Dmello

Reputation: 3

If You are using foreign key between vehicle and driver ,you just need to delete the child table entry or make reference Null.Is driver_id nullable. In migration try this, $table->integer('driver_id ')->unsigned()->nullable()->default(null); Hope this solves your issue.

Upvotes: 0

Christian
Christian

Reputation: 1798

I think you need:

$vehicle->driver_id = NULL;
$vehicle->save();

Upvotes: 2

Related Questions