Sandip Jha
Sandip Jha

Reputation: 75

Can i use if condition on laravel database query?

Can i use if condition inside query, I want to use filter when $request->review = 7 it will show 7 days data and else condition default 30 days data .

$reviews = Review::orderBy('created_at', 'DESC')
    ->orWhere('created_at', '>=', if($request->review == "7"){ $month = 7 })
    ->where('listing_id', $id)
    ->where('user_id', Auth::User()->id)
    ->paginate(6, ['*'], 'review');

Upvotes: 1

Views: 650

Answers (4)

adeel shairf
adeel shairf

Reputation: 1

$reviews = Review::orderBy('created_at', 'DESC');

if ($request->review == "7") {

$reviews->orWhere('created_at','>=', 7));

} $reviews = $reviews->where('listing_id', $id)

->where('user_id', Auth::User()->id)

->paginate(6, ['*'], 'review');

Upvotes: 0

JoshGray
JoshGray

Reputation: 95

$reviews = Review::where('listing_id', $id)
                 ->where('user_id', Auth::user()->id);

if($request->review == 7){
    $reviews->Where('created_at','>=',now()->subDays($request->review));
}

if($request->review != 7){
    $reviews->Where('created_at','>=',now()->subDays(30));
}

$reviews->orderBy('created_at', 'DESC')
        ->paginate(6, ['*'], 'review');

After understanding the above, you can go ahead to simplify the above using the ternary operator as you have below.

$reviews = Review::where('listing_id', $id)
    ->where('user_id', Auth::user()->id);
    ->Where('created_at','>=',now()->subDays(($request->review == 7)? 7 : 30));
    ->orderBy('created_at', 'DESC')
    ->paginate(6, ['*'], 'review');

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You could use something like this:

$reviews = Review::orderBy('created_at', 'DESC')
    ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30)
    ->where('listing_id', $id)
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

but keep in mind you might still get wrong results.

You should make sure brackets are added into query in correct place, otherwise you might get other user's results, so it's quite possible in fact you would like to use something like this:

$reviews = Review::orderBy('created_at', 'DESC')
    ->where(function($q) use ($request) {
      $q->where('listing_id', $id)
         ->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30)
    })
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

but you haven't explained what exact results you want to get from database so it's just a hint.

Upvotes: 1

Levente Otta
Levente Otta

Reputation: 795

You can split Eloquent Builder by cursor.

$cursor = Review::orderByDesc('created_at');

if ($request->review == "7") {
    $cursor->orWhere('created_at','>=', 7));
}
$reviews = $cursor->where('listing_id', $id)
    ->where('user_id', Auth::user()->id)
    ->paginate(6, ['*'], 'review');

Upvotes: 0

Related Questions