Created
December 19, 2016 12:17
-
-
Save stidges/16fe496308a9853d1e36d4ccc516b3cf to your computer and use it in GitHub Desktop.
Using when() in the Laravel query builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Post; | |
use Illuminate\Http\Request; | |
class PostsController extends Controller | |
{ | |
public function index(Request $request) | |
{ | |
$statusFilter = $request->get('status_filter'); | |
$posts = Post::when($statusFilter, function($builder) use ($statusFilter) { | |
// This where clause is only applied when the `status_filter` field was present in the request. | |
return $builder->where('status', $statusFilter); | |
})->get(); | |
// Usage with a default (available since v5.3.10) | |
$posts = Post::when($statusFilter, function($builder) use ($statusFilter) { | |
// This where clause is only applied when the `status_filter` field was present in the request. | |
return $builder->where('status', $statusFilter); | |
}, function($builder) { | |
// This where clause is only applied when the `status_filter` field was NOT present in the request. | |
return $builder->where('status', 'published'); | |
})->get(); | |
return $posts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment