0

I have little confusion around how to check the $user is a User object in Laravel.

$user = Apiato::call('User@FindUsersbytask', [$request->id]);
if($user) {   // here i have to check weather the $user is a user object or not
    Apiato::call('User@deleteuserTask', [$request->id]);
    ...
Kamafeather
  • 8,663
  • 14
  • 69
  • 99
Code cracker
  • 316
  • 1
  • 5
  • 20

2 Answers2

5

If what you want is to make sure the variable $user is an instance of the class User, then:

if ($user instanceof User) {
    ...
}

Otherwise, if it's just supposed to be any object, then you can use:

if (is_object($user)) {
    ...
}

although this will be true for an instance of any object, so you can't safely call methods or access properties that are present on the User class, for example.

NerdOfLinux
  • 1,017
  • 10
  • 24
  • 1
    I would add to **not forget to include the `User` class from the correct namespace** (via `use Name\Space\To\User;`); otherwise PHP compares the `instanceof` with `NamespaceOfTheCurrentCode\User`; while the OP probably wants something like `App\Entity\User`. – Kamafeather Oct 12 '21 at 18:04
2

Try this way

if(is_object($user))
Mainul Hasan
  • 691
  • 3
  • 12
  • my $user object calls one function called FindUserByTask it can return the object based on ID or it returns exception,Now my doubt is exception is not considered as an a object right..? – Code cracker Oct 12 '21 at 11:59
  • It depends on how it returns. If it returns as an object, then it will consider an object. – Mainul Hasan Oct 12 '21 at 12:05
  • If it is an `\Exception` (the name for PHP "errors") then it will just halt the code and return the error message. Because there is no possibility to proceed without a valid `User` object. **Pro tip:** I would avoid to wrap the code into a `try / catch` block because, if the user doesn't exist in the database, you won't anyway be able to recover from this exception. Just let it fail, like it should, and assume that you have that user initialized. – Kamafeather Oct 12 '21 at 18:09