skip to Main Content

I want to fetch data from the database using laravel by using multiple conditions. The query must look for the different conditions in same columns and grab the result.

Table looks like this

Item Position Gender
A All All
B Permanent All
C All Female
D All Male
E Temporary All

I want to fetch the data where the position category can either be All or user-specific and gender can either be all or user-specific. The user-specific position and gender values can be obtained from the logged in user’s details.
If user position is "Permanent" and gender is "Male" then the results should look like

Item Position Gender
A All All
B Permanent All
D All Male

I need a query to get the result.

2

Answers


  1. You can use the Eloquent ORM to build a query with multiple conditions. So Firstly get details of the logged user by using Auth and pass the params to where condition. Check below the code.

    use AppModelsItem;
    use IlluminateSupportFacadesAuth;
    
    $userPosition = Auth::user()->position;
    $userGender = Auth::user()->gender;
    
    $items = Item::where(function($query) use ($userPosition) {
            $query->where('position', 'All')
                  ->orWhere('position', $userPosition);
        })
        ->where(function($query) use ($userGender) {
            $query->where('gender', 'All')
                  ->orWhere('gender', $userGender);
        })
        ->get();
    
    Login or Signup to reply.
  2. You can use whereIn():

    $items = Item::whereIn('position', ['All', $userPosition])
            ->whereIn('gender', ['All', $userGender])
            ->get();
    

    which will produce the following prepared statement:

    select * from `items` where `position` in (?, ?) and `gender` in (?, ?)
    

    and then execute it with the provided values – ['All', 'Permanent', 'All', 'Male']

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search