A Simple Collection Trick: Using flip() in Laravel
Laravel Collections provide many useful methods, and one of the most overlooked is:
flip()
It allows you to swap keys and values instantly.
Basic Example
$roles = collect([
1 => 'Admin',
2 => 'Manager',
3 => 'Customer',
]);
$roles->flip();
Output:
collect([
'Admin' => 1,
'Manager' => 2,
'Customer' => 3,
]);
Real Project Example
Imagine you receive role data:
$roles = [
1 => 'Admin',
2 => 'Editor',
3 => 'Customer',
];
You need to quickly find the ID of a role:
$roleId = collect($roles)
->flip()
->get('Editor');
Result:
2
No loops.
No manual searching.
Another Practical Example
Convert country mappings:
$countries = collect([
'IN' => 'India',
'US' => 'United States',
]);
Need the country code?
$code = $countries
->flip()
->get('India');
Result:
IN
Important Note
Values must be unique.
Example:
collect([
1 => 'Admin',
2 => 'Admin',
])->flip();
Only the last matching key will remain.
When to Use flip()
Use it when:
- Creating lookup tables
- Converting labels to IDs
- Reversing configuration mappings
- Avoiding manual array searches