To handle multiple requests to the same resource with specific requirements, you can use a combination of query parameters and policies to differentiate between the types of users and their respective data access needs. Here's a general approach you can take:
- Use query parameters to specify sorting and filtering options.
- Implement authorization logic to determine what data a user can access.
- Apply sorting and filtering within your controller based on the user's role and the provided query parameters.
Here's an example of how you might implement this in your InvoiceController:
use Illuminate\Http\Request;
use App\Models\Invoice;
use Illuminate\Support\Facades\Auth;
class InvoiceController extends Controller
{
public function index(Request $request)
{
// Get the authenticated user
$user = Auth::user();
// Start with a base query
$query = Invoice::query();
// If the user is a company, they can see all invoices
if ($user->isCompany()) {
// Apply sorting by date for company users
$query->orderBy('date', 'desc');
} elseif ($user->isCustomer()) {
// If the user is a customer, they can only see their own invoices
$query->where('customer_id', $user->id);
// Apply sorting by status for customer users
$query->orderBy('status', 'asc');
} else {
// Handle other types of users or guests, if necessary
abort(403, 'Unauthorized access');
}
// Execute the query and get the results
$invoices = $query->get();
// Return the invoices as a resource collection or in your preferred format
return response()->json($invoices);
}
}
In this example, we're assuming that the User model has methods isCompany() and isCustomer() to determine the type of user. You would need to implement these methods based on your application's logic.
Additionally, you may want to use Laravel's policy system to authorize actions on the Invoice model. This would allow you to define complex authorization logic in a dedicated class, keeping your controller clean and focused on handling the request.
Remember to also validate the query parameters and ensure that you're protecting against unauthorized access to data. Always consider security implications when implementing filtering and sorting based on user roles.