Check if Relationship Method Exists in Laravel

Updated 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