PA060
PA060

Reputation: 59

laravel 5.2 if else to query database

stuck on a form that allows the user to enter a value into a choice of two fields. I can query the database using one field but want to add more range to database queries. With the following code below when i try to access the page to query it just shows me a white screen.

public function index()
 {
   $data = $request->all();

   if(!empty($data['pstoreNum']))
   {
   $pstoreNum = $data['pstoreNum'];


    $result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
              ->get();

    return view('perfumes',compact('result'));
  } 
  else if(!empty($data['pweekNum']))
  {
      $pweekNum = $data['pweekNum'];


      $result = DB::table('perfumes')->where('WeekNumber','=',$pweekNum)
             ->get();

       return view('perfumes',compact('result'));
   }

  }

My routes file simple calls the index function. Any help would be appreciated.

Upvotes: 0

Views: 596

Answers (1)

Chris Townsend
Chris Townsend

Reputation: 2716

You can add query functions within your query like so

public function index(Request $request)
{
    $data = $request->all();

    $result = \DB::table('perfumes')->where(function($query) use ($data) {
        if(!empty($data['pstoreNum'])) {
            $query->where('StoreNumber', '=', $data['pstoreNum']);
        }
        if(!empty($data['pweekNum'])) {
            $query->where('WeekNumber', '=', $data['pweekNum']);
        }
    })->get();

    return view('perfumes',compact('result'));

  }

You can then use the one query and add multiple wheres on various conditions.

https://laravel.com/docs/5.2/queries#advanced-where-clauses

Upvotes: 1

Related Questions