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

muuucho's avatar
Level 11

Eloquent sync security

I have 3 tables: companies, tags and pivot company_tags. On a comany update from a form I have a multiselect for tags so I like to sync the tags for the company, so I write

$this->company->tags()->sync($this->tags);

However, my app is multi-tenant, so each company and each tag in my app belongs to a team. This means that when I sync, I need to - for security reasons - verify that each of the elements in $this->tags has a team_id of Auth::user()->team_id How can this be achieved?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To ensure that the tags being synced belong to the same team as the authenticated user, you can filter the tags before performing the sync operation. Here's how you can achieve this:

  1. Retrieve the authenticated user's team ID.
  2. Filter the tags to include only those that belong to the same team.
  3. Sync the filtered tags with the company.

Here's a code example to illustrate this:

use Illuminate\Support\Facades\Auth;

class CompanyController extends Controller
{
    public function update(Request $request, Company $company)
    {
        // Retrieve the authenticated user's team ID
        $teamId = Auth::user()->team_id;

        // Filter the tags to include only those that belong to the same team
        $filteredTags = Tag::whereIn('id', $request->tags)
                            ->where('team_id', $teamId)
                            ->pluck('id')
                            ->toArray();

        // Sync the filtered tags with the company
        $company->tags()->sync($filteredTags);

        // Continue with the rest of your update logic
        // ...

        return redirect()->route('companies.show', $company);
    }
}

In this example:

  • We first retrieve the authenticated user's team ID.
  • We then filter the tags by checking if their team_id matches the authenticated user's team ID.
  • Finally, we sync the filtered tags with the company.

This ensures that only tags belonging to the same team as the authenticated user are synced with the company, thus maintaining the security of your multi-tenant application.

Please or to participate in this conversation.