HUGE_DICK_10_INCHES's avatar

How t check is param collection or object

I created custom notifications model with two params, notification and user/users. I tried to check if it is object or collection but it always returns as object.

public function send($notification, $users) {
        if(!is_null($users) && is_object($users)) {
          $this->create([
              'user_id' => $notification['user_id'],
              'foruser_id' => $users->id,
              'type_id' => $notification['type'],
              'info' => $notification['info'],
          ]);
        } else if(!empty($users)) {
            foreach($users as $user) {
                $this->create([
                    'user_id' => $notification['user_id'],
                    'foruser_id' => $user->id,
                    'type_id' => $notification['type'],
                    'info' => $notification['info'],
                ]);
            }
        }
    }

How can I check if I passed something like:

User::find($id) or User::where('id', '!=', auth()->user()->id)->get()

0 likes
4 replies
jove's avatar

How do you use your function?

Not sure what you mean by this

How can I check if I passed something like: User::find($id) or User::where('id', '!=', auth()->user()->id)->get()

Nakov's avatar

What about using instanceof, because both a collection or a model are objects:

use Illuminate\Support\Collection; // at the top

if ($users instanceof Collection) ...

if ($users instanceof App\User) ...
shez1983's avatar

ok so what i think you should do is move the $users out of the func. only pass in EITHER a USER or multiple users not both..

i would prefer a single user being passed in. then outside the func where its called u will/should know if u have one user or more.

Alternatively do what laravel does.. always pass in array.. even if its one check inside the send() and create an array and then just do the loop..

tykus's avatar
tykus
Best Answer
Level 104

A Collection is an object.

You use instanceof to check if the variable is a particular class instance.

if($users && $users instanceof App\User) {

    //  single user

} else if ($users instanceof Illuminate\Database\Eloquent\Collection) {
    
    // multiple users

}

You can make the code even cleaner by simply wrapping whatever you receive in a collection:

public function send($notification, $users)
{
    collect($users)->each(function ($user) use ($notification) {
        $this->create([
            'user_id' => $notification['user_id'],
            'foruser_id' => $user->id,
            'type_id' => $notification['type'],
            'info' => $notification['info'],
        ]);
    });
}

Now, whether you received null, a User instance or a Collection of User instances, you are good.

3 likes

Please or to participate in this conversation.