1

How can I check if my form input value exist in controller array?

Code

$admins = User::role(['admin', 'superadmin'])->pluck('id'); // get array of admins id

if($request->input('user_id') == $admins) { // if user_id is include admins id...
 // do something
} else {
 // do something else
}

4 Answers 4

4

Use in_array (docs) to check whether something exists in an array.

if(in_array($request->input('user_id'), $admins)) { // if user_id is include admins id

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

if(in_array($request->input('user_id'), $admins)) { // if user_id is include admins id...
 // do something
} else {
 // do something else
}

Comments

1

You could as well perform it in a single query:

$user_admin = User::role(['admin', 'superadmin'])->find($request->input('user_id')); // returns null if not found or the $user if found

if($user_admin) { /
 // do something
} else {
 // do something else
}

Comments

0

If you are working with collections you can use their methods.

In this case you could use contains() method.

$admins = User::role(['admin', 'superadmin'])->pluck('id'); //this return a collection

if($admins->contains($request->input('user_id'))) { // use the contains method of collection
 // do something
} else {
 // do something else
}

4 Comments

->pluck() returns a native array, not a collection. Using ->contains() will throw an error.
@Joundill Hi! Could you tell me what error it gives you?
Uncaught Error: Call to a member function contains() on array
@Joundill Maybe I'm wrong but, the pluck () function should return a collection not an array. You could use collect () helper to make it a collection but if it is an array you have reason to use in_array as you have commented. thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.