3

Eg. Region and City are two models. Relations are defined as below:

Region.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Region extends Model
{
    public function cities() {
        return $this->hasMany('App\City');
    }
}

City.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    public $timestamps = false;

    public function region() {
        return $this->belongsTo('App\Region');
    }
}

Region can have multiple cities but a city can be associated with a single Region only. For this, I am having a list of cities already added but want to attach city with the region on the details page of a region just like if we have a many-to-many relationship. How to validate and not allow to attach city to region which is already attached to any other region?

Bharat Jain
  • 500
  • 3
  • 15

1 Answers1

0

You would need to create a custom method on the model to achieve something like this. Here is an example of how you might want to do it

City.php

public function attachToRegion(Region $region) {
    if ($this->region) {
        throw new CityAlreadyAttachedException();
    }

    $this->update(['region_id' => $region->id]);
}

You would then call this within your repository/service/controller and catch the exception if the city model is already attached to the region model. For example:

try {
    $region = Region::first();
    $city = City::first()->attachToRegion($region);
} catch (CityAlreadyAttachedException $e) {
    // The city is already attached. Handle the error here
}
George Hanson
  • 2,940
  • 1
  • 6
  • 18