Filter Records by query on relations in Laravel












0















I need to get only those users that have role name "Team Leader".



user table : role_id
role_table : role_name


For example:



   $role = Role::where('name', 'Team Leader')->first();
$team_leaders = User::where('role_id',$role->id)->get();


how can i do this directly with query on relationship. Thanks in Advanve










share|improve this question



























    0















    I need to get only those users that have role name "Team Leader".



    user table : role_id
    role_table : role_name


    For example:



       $role = Role::where('name', 'Team Leader')->first();
    $team_leaders = User::where('role_id',$role->id)->get();


    how can i do this directly with query on relationship. Thanks in Advanve










    share|improve this question

























      0












      0








      0


      0






      I need to get only those users that have role name "Team Leader".



      user table : role_id
      role_table : role_name


      For example:



         $role = Role::where('name', 'Team Leader')->first();
      $team_leaders = User::where('role_id',$role->id)->get();


      how can i do this directly with query on relationship. Thanks in Advanve










      share|improve this question














      I need to get only those users that have role name "Team Leader".



      user table : role_id
      role_table : role_name


      For example:



         $role = Role::where('name', 'Team Leader')->first();
      $team_leaders = User::where('role_id',$role->id)->get();


      how can i do this directly with query on relationship. Thanks in Advanve







      laravel laravel-query-builder






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 1 at 7:55









      NehaNeha

      282216




      282216
























          3 Answers
          3






          active

          oldest

          votes


















          4














          IN User model you should add relation method 'role'



          class User extends Authenticatable
          {

          public function role()
          {
          return $this->belongsTo(Role::class, 'role_id');
          }

          }


          And then you can do:



          User::whereHas('role', function ($query) {
          $query->where('role_name', '=', 'Team Leader');
          })->get();





          share|improve this answer































            3














            You can define one to many relationship,
            In your Role model,



            class Role extends Model
            {
            public function users()
            {
            return $this->hasMany(User::class, 'role_id');
            }

            }


            in your User Model,



            class User extends Authenticatable
            {

            public function role()
            {
            return $this->belongsTo(Role::class, 'role_id');
            }

            }


            Now you can get the users list of team leader,



            $role = Role::where('name', 'Team Leader')->first();
            $team_leaders = $role->users;


            Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many






            share|improve this answer































              1














              One way of doing this is through Query Scopes.



              For example:



              public function scopeTeamLeader($query)
              {
              $role = Role::whereName('Team Leader')->first();

              return $query->where('role_id', $role->id);
              }


              To query Users who are then also Team Leaders, you can do something like this



              User::latest()
              ->TeamLeader()
              ->get();


              I would also probably define some class constants in my 'AppRole' class.
              For example.



              class Role 
              {
              const TEAM_LEADER = 1;
              }


              The following could then be cleaned up like this:



              public function scopeTeamLeader($query)
              {
              return $query->where('role_id', Role::TEAM_LEADER);
              }


              Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)






              share|improve this answer

























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993900%2ffilter-records-by-query-on-relations-in-laravel%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                4














                IN User model you should add relation method 'role'



                class User extends Authenticatable
                {

                public function role()
                {
                return $this->belongsTo(Role::class, 'role_id');
                }

                }


                And then you can do:



                User::whereHas('role', function ($query) {
                $query->where('role_name', '=', 'Team Leader');
                })->get();





                share|improve this answer




























                  4














                  IN User model you should add relation method 'role'



                  class User extends Authenticatable
                  {

                  public function role()
                  {
                  return $this->belongsTo(Role::class, 'role_id');
                  }

                  }


                  And then you can do:



                  User::whereHas('role', function ($query) {
                  $query->where('role_name', '=', 'Team Leader');
                  })->get();





                  share|improve this answer


























                    4












                    4








                    4







                    IN User model you should add relation method 'role'



                    class User extends Authenticatable
                    {

                    public function role()
                    {
                    return $this->belongsTo(Role::class, 'role_id');
                    }

                    }


                    And then you can do:



                    User::whereHas('role', function ($query) {
                    $query->where('role_name', '=', 'Team Leader');
                    })->get();





                    share|improve this answer













                    IN User model you should add relation method 'role'



                    class User extends Authenticatable
                    {

                    public function role()
                    {
                    return $this->belongsTo(Role::class, 'role_id');
                    }

                    }


                    And then you can do:



                    User::whereHas('role', function ($query) {
                    $query->where('role_name', '=', 'Team Leader');
                    })->get();






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 1 at 8:19









                    Andrey SvyrydovAndrey Svyrydov

                    1264




                    1264

























                        3














                        You can define one to many relationship,
                        In your Role model,



                        class Role extends Model
                        {
                        public function users()
                        {
                        return $this->hasMany(User::class, 'role_id');
                        }

                        }


                        in your User Model,



                        class User extends Authenticatable
                        {

                        public function role()
                        {
                        return $this->belongsTo(Role::class, 'role_id');
                        }

                        }


                        Now you can get the users list of team leader,



                        $role = Role::where('name', 'Team Leader')->first();
                        $team_leaders = $role->users;


                        Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many






                        share|improve this answer




























                          3














                          You can define one to many relationship,
                          In your Role model,



                          class Role extends Model
                          {
                          public function users()
                          {
                          return $this->hasMany(User::class, 'role_id');
                          }

                          }


                          in your User Model,



                          class User extends Authenticatable
                          {

                          public function role()
                          {
                          return $this->belongsTo(Role::class, 'role_id');
                          }

                          }


                          Now you can get the users list of team leader,



                          $role = Role::where('name', 'Team Leader')->first();
                          $team_leaders = $role->users;


                          Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many






                          share|improve this answer


























                            3












                            3








                            3







                            You can define one to many relationship,
                            In your Role model,



                            class Role extends Model
                            {
                            public function users()
                            {
                            return $this->hasMany(User::class, 'role_id');
                            }

                            }


                            in your User Model,



                            class User extends Authenticatable
                            {

                            public function role()
                            {
                            return $this->belongsTo(Role::class, 'role_id');
                            }

                            }


                            Now you can get the users list of team leader,



                            $role = Role::where('name', 'Team Leader')->first();
                            $team_leaders = $role->users;


                            Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many






                            share|improve this answer













                            You can define one to many relationship,
                            In your Role model,



                            class Role extends Model
                            {
                            public function users()
                            {
                            return $this->hasMany(User::class, 'role_id');
                            }

                            }


                            in your User Model,



                            class User extends Authenticatable
                            {

                            public function role()
                            {
                            return $this->belongsTo(Role::class, 'role_id');
                            }

                            }


                            Now you can get the users list of team leader,



                            $role = Role::where('name', 'Team Leader')->first();
                            $team_leaders = $role->users;


                            Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 1 at 8:16









                            Md.Sukel AliMd.Sukel Ali

                            1,1681716




                            1,1681716























                                1














                                One way of doing this is through Query Scopes.



                                For example:



                                public function scopeTeamLeader($query)
                                {
                                $role = Role::whereName('Team Leader')->first();

                                return $query->where('role_id', $role->id);
                                }


                                To query Users who are then also Team Leaders, you can do something like this



                                User::latest()
                                ->TeamLeader()
                                ->get();


                                I would also probably define some class constants in my 'AppRole' class.
                                For example.



                                class Role 
                                {
                                const TEAM_LEADER = 1;
                                }


                                The following could then be cleaned up like this:



                                public function scopeTeamLeader($query)
                                {
                                return $query->where('role_id', Role::TEAM_LEADER);
                                }


                                Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)






                                share|improve this answer






























                                  1














                                  One way of doing this is through Query Scopes.



                                  For example:



                                  public function scopeTeamLeader($query)
                                  {
                                  $role = Role::whereName('Team Leader')->first();

                                  return $query->where('role_id', $role->id);
                                  }


                                  To query Users who are then also Team Leaders, you can do something like this



                                  User::latest()
                                  ->TeamLeader()
                                  ->get();


                                  I would also probably define some class constants in my 'AppRole' class.
                                  For example.



                                  class Role 
                                  {
                                  const TEAM_LEADER = 1;
                                  }


                                  The following could then be cleaned up like this:



                                  public function scopeTeamLeader($query)
                                  {
                                  return $query->where('role_id', Role::TEAM_LEADER);
                                  }


                                  Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)






                                  share|improve this answer




























                                    1












                                    1








                                    1







                                    One way of doing this is through Query Scopes.



                                    For example:



                                    public function scopeTeamLeader($query)
                                    {
                                    $role = Role::whereName('Team Leader')->first();

                                    return $query->where('role_id', $role->id);
                                    }


                                    To query Users who are then also Team Leaders, you can do something like this



                                    User::latest()
                                    ->TeamLeader()
                                    ->get();


                                    I would also probably define some class constants in my 'AppRole' class.
                                    For example.



                                    class Role 
                                    {
                                    const TEAM_LEADER = 1;
                                    }


                                    The following could then be cleaned up like this:



                                    public function scopeTeamLeader($query)
                                    {
                                    return $query->where('role_id', Role::TEAM_LEADER);
                                    }


                                    Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)






                                    share|improve this answer















                                    One way of doing this is through Query Scopes.



                                    For example:



                                    public function scopeTeamLeader($query)
                                    {
                                    $role = Role::whereName('Team Leader')->first();

                                    return $query->where('role_id', $role->id);
                                    }


                                    To query Users who are then also Team Leaders, you can do something like this



                                    User::latest()
                                    ->TeamLeader()
                                    ->get();


                                    I would also probably define some class constants in my 'AppRole' class.
                                    For example.



                                    class Role 
                                    {
                                    const TEAM_LEADER = 1;
                                    }


                                    The following could then be cleaned up like this:



                                    public function scopeTeamLeader($query)
                                    {
                                    return $query->where('role_id', Role::TEAM_LEADER);
                                    }


                                    Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jan 1 at 8:22

























                                    answered Jan 1 at 8:16









                                    MozammilMozammil

                                    6,220420




                                    6,220420






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993900%2ffilter-records-by-query-on-relations-in-laravel%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        How to fix TextFormField cause rebuild widget in Flutter

                                        Npm cannot find a required file even through it is in the searched directory