Last active
July 7, 2021 02:46
-
-
Save einnar82/e1f86d22069bce8c2ee4633a8ddce7a0 to your computer and use it in GitHub Desktop.
Pipeline Pattern in Laravel (Queries)
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\API; | |
use App\Http\Controllers\Controller; | |
use App\Models\ActivityLog; | |
use App\QueryFilters\FilterByUser; | |
use Illuminate\Http\Request; | |
use Illuminate\Pipeline\Pipeline; | |
class ActivityLogController extends Controller | |
{ | |
/** | |
* Display a listing of the resource. | |
*/ | |
public function index(Request $request) | |
{ | |
# I'm creating an API endpoint that gets all activity log | |
# based on the query params that passed in the URL. | |
# example: localhost:8000/api/activity-logs?user_id=1 | |
# Take a look on his explanation regarding pipelines. | |
# https://jeffochoa.me/understanding-laravel-pipelines | |
$activityLogs = app(Pipeline::class) | |
->send(ActivityLog::query()) | |
->through([ | |
FilterByUser::class | |
]) | |
->thenReturn() | |
->paginate(); | |
return $activityLogs; | |
} |
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\QueryFilters; | |
class FilterByUser | |
{ | |
public function handle($query, $next) | |
{ | |
if(request()->has('user')) { | |
$query->where('user_id', request('user')); | |
} | |
if(request()->has('user_id')) { | |
$query->where('user_id', request('user_id')); | |
} | |
return $next($query); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment