Check if Relationship Method Exists in Laravel

Created at 09-Apr-2021 , By samar

Check if Relationship Method Exists in Laravel

With this article, we’ll look at some examples of how to address the "Check if Relationship Method Exists in Laravel" problem.

  • Eloquent relationship method exists or not in laravel

    $user = User::where('id', 1)->first();
    if (method_exists($user, 'roles')) {
        // Do something with $user->roles()->
    }
    

    If your eloquent relationship method names are dynamic and you need to check if Relationship method with such name exists on the object, use method_exists($object, 'method_name') function. It returns true if the method with this particular name exists else return false.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.