Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

p4rz1val's avatar

Preventing pivot record from being deleted

I'm trying to verify technologies for profiles i do this manually from the admin panel, also users can add or remove technologies, BUT if the technology is already verified they shouldn't be able to remove it.

What im doing righ now is to have two different relationships "technologies" and "verifiedTechnologies"

public function technologies(): BelongsToMany
{
    return $this->belongsToMany(Technology::class)
        ->using(ProfileTechnology::class)
        ->withTimestamps()
        ->wherePivot('verified', false)
        ->withPivot(['type', 'verified']);
}

public function verifiedTechnologies(): BelongsToMany
{
    return $this->belongsToMany(Technology::class)
        ->using(ProfileTechnology::class)
        ->withTimestamps()
        ->wherePivot('verified', true)
        ->withPivot(['type', 'verified']);
}								

public function allTechnologies()
{
    return $this->verifiedTechnologies->concat($this->technologies);
}

i don't like this approach for a couple reasons, first of all when i need to present the technologies i need to concat both collections, when i'm trying to eager load i always need to eager load both, on nova if i'm presenting the relationship (i guess you can customize the query) but i need to create two relationship's, etc.

profile
    id - integer
 
technology
    id - integer
 
profile_technology
    id - integer
    profile_id - integer
    technology_id - integer
    verified - boolean

Any ideas how would you approach something like this?

0 likes
3 replies
MohamedTammam's avatar

Why are you checking against verified everywhere when you only need it when the user tries to delete the technology?

p4rz1val's avatar

@MohamedTammam To prevent deleting, so basically if anyone does something like this on the code:

$profile->technologies()->sync([])

nothing gets deleted, in a sense is more like a global scope

MohamedTammam's avatar

@p4rz1val In that case I would refactor the code the be something like that

public function technologies(): BelongsToMany
{
    return $this->allTechnologies(Technology::class)->wherePivot('verified', false);
}

public function verifiedTechnologies(): BelongsToMany
{
    return $this->allTechnologies(Technology::class)->wherePivot('verified', true);
}								

public function allTechnologies()
{
    return $this->belongsToMany(Technology::class)
        ->using(ProfileTechnology::class)
        ->withTimestamps()
        ->withPivot(['type', 'verified']);
}

With that, you don't need to contact or do multiple queries when you're fetching all technologies.

Please or to participate in this conversation.