In Laravel, can you check if an object is in a collection using the object's primary key?
I need a quick way to find out if an object is in a collection. I am creating a template where an administrator can assign a user role. The statement below is essentially what I am trying to accomplish.
Is a role with a primary key value of 5 in this role set.
What I am doing (obviously dipped in one file):
<?php
// The user
$user = User::find(1);
// Array of roles the user is associated with. Fetched via a pivot table
$tmpUserRoles = $user->roles->toArray();
// Rebuilds the values from $tmpUserRoles so that the array key is the primary key
$userRoles = array();
foreach ($tmpUserRoles as $roleData) {
$userRoles[$roleData['role_id']] = $roleData;
}
// This loop is used in the view. Once again, this is dumbed down
foreach ($Roles as $role) {
if (isset($userRoles[$role->role_id]) {
echo $user->firstName.' is a '.$role->label;
} else {
echo $user->firstName.' is not a '.$role->label;
}
}
Quoting over an array just to create an identical array with a primary key, as the index seems like a big waste of time. Is there an easier way in Laravel to tell if an object is contained in a collection using the object's primary key?
source to share
Use $tmpUserRoles->contains(5)
to check if a primary key exists in your collection 5
. (See http://laravel.com/docs/4.2/eloquent#collections )
source to share
The selected answer looks like it works.
If you want a more readable way of testing if the object is an instance of a laravel collection class (or any class in general), you can use php is_a()
:
// This will return true if $user is a collection
is_a($user, "Illuminate\Database\Eloquent\Collection");
It doesn't infer what you also want to do in your question description, but it might be useful in general.
source to share