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:
- Retrieve the authenticated user's team ID.
- Filter the tags to include only those that belong to the same team.
- 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_idmatches 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.