Skip to content

Instantly share code, notes, and snippets.

@stidges
Created December 19, 2016 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stidges/16fe496308a9853d1e36d4ccc516b3cf to your computer and use it in GitHub Desktop.
Save stidges/16fe496308a9853d1e36d4ccc516b3cf to your computer and use it in GitHub Desktop.
Using when() in the Laravel query builder
<?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