Adding Search and Filtering
Why Add Search and Filtering?
Section titled “Why Add Search and Filtering?”Search and filtering are important features that help users quickly find what they need in your application. As the data managed by the application data grows, these features become essential for maintaining a good user experience.
Why Add Search and Filtering?
- Improved user experience: Users can find information quickly instead of scrolling through long lists or cycle through all pages,
- Better performance: Display only relevant results instead of loading all data,
- Increased engagement: Users interact more with applications that help them find content efficiently.
This guide walks you through implementing search and filtering functionality in your Slim MVC application.
Understanding Search vs Filtering
Section titled “Understanding Search vs Filtering”It’s important to understand the difference between search and filtering before implementing these features:
Search
Section titled “Search”- What: Text-based queries that look for matches in content
- User Input: Free-text search box where users type keywords
- Database: Usually uses LIKEqueries or full-text search
- Examples:
- Searching for “laptop” in product names/descriptions
- Finding users by typing part of their name
- Looking for posts containing specific words
 
Filtering
Section titled “Filtering”- What: Narrowing results based on predefined criteria
- User Input: Dropdowns, checkboxes, radio buttons, date pickers
- Database: Uses exact matches with WHEREclauses
- Examples:
- Filter by category (Electronics, Clothing, Books)
- Filter by status (Active, Inactive, Pending)
- Filter by date range or price range
 
Combined Approach
Section titled “Combined Approach”Most applications use both search and filtering together:
- Search box for text queries: “Find products containing ‘gaming’”
- Filters for structured data: “In Electronics category”, “Under $500”, “In stock only”
Advanced: Adding Search and Filtering
Section titled “Advanced: Adding Search and Filtering”Step 1: Extend Your Model for Search
Section titled “Step 1: Extend Your Model for Search”- Add search methods to your model class:
- search($criteria)=> Search with multiple filters
- getFiltered($filters)=> Apply specific filters
- getAllPaginated($page, $limit, $search)=> Paginated results with search
 
- Keep all data logic in the model following MVC pattern
Step 2: Modify Your Index Route
Section titled “Step 2: Modify Your Index Route”- Update your controller’s index method to accept search parameters
- Get search terms from query parameters using $request->getQueryParams()
- Pass search parameters to your model’s search methods
- Pass current search values back to the view for form persistence
Step 3: Create Search Form
Section titled “Step 3: Create Search Form”- Add a search form to your index.phpview
- Use GET method so search parameters appear in URL
- Make form fields retain their values using passed data
- Include filter options (dropdowns, checkboxes) as needed
Step 4: Implement Filtering Logic
Section titled “Step 4: Implement Filtering Logic”Basic Search Implementation (in Controller):
- Extract search parameters from query string
- Validate and sanitize search inputs
- Pass validated parameters to your model’s search methods
- Get filtered results from model and pass to view
Model Implementation:
- Create search methods in your model that handle data filtering
- Keep all database queries and data logic in the model
- Return structured data back to the controller
Common Filter Types:
- Text Search: Search in specific fields (name, description, etc.)
- Category Filter: Dropdown with predefined options
- Date Range: Start and end date filtering
- Status Filter: Active/inactive, published/draft, etc.
- Sorting: Order by different fields (name, date, price, etc.)
Step 5: Handle Empty Results
Section titled “Step 5: Handle Empty Results”- Check if filtered results are empty
- Display appropriate message to user
- Provide option to clear filters
- Show total count of results
Step 6: Add Pagination (Optional)
Section titled “Step 6: Add Pagination (Optional)”- Add pagination methods to your model (e.g., getAllPaginated($page, $limit, $filters))
- Calculate total number of filtered results in the model
- Determine current page from query parameters in controller
- Call model’s pagination methods with search filters
- Generate pagination links in view that preserve search parameters
Search Route Examples
Section titled “Search Route Examples”// Your existing index route handles search automatically$app->get('/products', [ProductController::class, 'index'])    ->setName('products.index');
// Optional: dedicated search route$app->get('/products/search', [ProductController::class, 'search'])    ->setName('products.search');Controller Implementation Tips
Section titled “Controller Implementation Tips”Getting Search Parameters:
- Use $request->getQueryParams()to get all query string data
- Provide default values for missing parameters
- Validate search inputs before using them
- Store search parameters to pass back to view
Preserving Search State:
- When redirecting after operations (create/update/delete), preserve search parameters
- Use $query_paramsin your redirect calls to maintain current search
- Include current page number if using pagination
Search URL Examples:
- Basic search: /products?search=laptop
- Multiple filters: /products?search=laptop&category=electronics&status=active
- With pagination: /products?search=laptop&page=2
- With sorting: /products?search=laptop&sort=price&order=asc
View Implementation Tips
Section titled “View Implementation Tips”Search Form Best Practices:
- Use GET method for search forms
- Include hidden fields for maintaining sort order
- Add “Clear Filters” link that goes to base index route
- Show current search criteria above results
- Display result count
User Experience:
- Show loading states for search operations
- Highlight search terms in results
- Provide search suggestions if possible
- Make it clear when no results are found
- Allow users to easily modify their search
Integration with Existing CRUD Operations
Section titled “Integration with Existing CRUD Operations”After Create/Update/Delete:
- Redirect back to index with preserved search parameters
- Use flash messages to show success/error feedback
- Maintain user’s current view state
Example Redirect After Delete:
// Preserve current search when redirecting$currentSearch = $request->getQueryParams();return $this->redirect($request, $response, 'products.index', [], $currentSearch);