How to apply eloquent relation conditionally

September 21, 2019

by Yunus Shaikh

There are several ways to add eloquent relation based on the condition, Lets see few options which will append the Eloquent relation based on user input.

Here is a snippet to apply laravel eloquent relation conditionally.

          $query = Author::query();
          $query->when(request('filter_by') == 'likes', function ($q) {
              return $q->where('likes', '>', request('likes_amount', 0));
          $query->when(request('filter_by') == 'date', function ($q) {
              return $q->orderBy('created_at', request('ordering_rule', 'desc'));
          $authors = $query->get();

Let's consider A situation that Users belong to the company, So from the input, if we get the Company field then we need to filter the user based on that company

Here is the Controller

              $user = User::withCompany()->get();

Now, We need to add Local Scope, which will be a function with scope suffix. the function name would be scopeWithCompany

. Let us create this function in Users.php the model.

          public function scopeWithCompany($query)
                  return $query->where('company_id',request()->get('company_id'));
              return $query;

Checkout Laravel's Official documents, Eloquent and Scopes.

Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with scope
Once the scope has been defined, you may call the scope methods when querying the model. However, you should not include the scope prefix when calling the method. You can even chain calls to various scopes

Featured Posts