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()
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()
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.
Please or to participate in this conversation.