I have two models EventLocation and EventDepartment. The models and relationship are shown below:
class EventLocation extends Model
{
public function event_departments()
{
return $this->hasMany(EventDepartment::class);
}
}
class EventDepartment extends Model
{
public function event_location()
{
return $this->belongsTo(EventLocation::class, 'location_id');
}
}
The migration for the EventDepartment contains the location_id as a foreign key as shown:
Schema::create('event_departments', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('location_id')->constrained('event_locations');
$table->softDeletes();
$table->timestamps();
});
The issue I am facing now is that, how do I make a column unique in the EventDepartment table when creating a new deparment based on the foreign key which is location_id?
i.e An EventDepartment cannot have columns with the same name if they belong to the same EventLocation but i'm able create another EventDepartment with an existing name as long as it belongs to a different EventLocation
I have tried with this but isn't working:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3|unique:event_departments,location_id',
'location_id' => 'required',
]);
$department = EventDepartment::create([
'name' => $request->name,
'location_id' => $request->location_id,
]);
return new EventDepartmentResource($department);
}