One solution to this problem would be to create a middleware that runs the global query and adds the resulting report listings to the request object. This middleware can then be applied to all controllers that need access to the report listings.
Here's an example implementation:
- Create a middleware class that runs the global query and adds the report listings to the request object:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class AddReportListingsToRequest
{
public function handle($request, Closure $next)
{
$user = Auth::user();
$role = $user->role; // assuming the user's role is stored in a 'role' column
// run the global query based on the user's role
$reportListings = DB::table('reports')
->where('department', $role)
->get();
// add the report listings to the request object
$request->merge(['reportListings' => $reportListings]);
return $next($request);
}
}
- Apply the middleware to all controllers that need access to the report listings:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FinancialController extends Controller
{
public function __construct()
{
$this->middleware('addReportListingsToRequest');
}
public function index(Request $request)
{
$reportListings = $request->reportListings;
// use the report listings in the view
return view('financial.index', compact('reportListings'));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LogisticsController extends Controller
{
public function __construct()
{
$this->middleware('addReportListingsToRequest');
}
public function index(Request $request)
{
$reportListings = $request->reportListings;
// use the report listings in the view
return view('logistics.index', compact('reportListings'));
}
}
This way, the global query is only run once for each request, and the resulting report listings are available to all controllers that need them.