Support Search by Coach

User
return view('content.admin.support.index', [
'supports' => Support::orderBy('created_at', 'desc')->paginate(config('pagination')),
'coachs'=>Coach::all()
]);
add search by coach id
Assistant
To add a search feature for filtering by coach ID in your Laravel application, you can modify your controller method to include a search parameter for filtering and update your view to include a form for submitting the search query.

### Controller Update
Modify your controller method to check for a search parameter and filter `supports` accordingly:

public function index(Request $request)
{
    $query = Support::query();

    // Filter by coach ID if a search parameter exists
    if ($request->has('coach_id') && !empty($request->coach_id)) {
        $query->where('coach_id', $request->coach_id);
    }

    return view('content.admin.support.index', [
        'supports' => $query->orderBy('created_at', 'desc')->paginate(config('pagination')),
        'coachs' => Coach::all(),
        'selectedCoach' => $request->coach_id // to maintain the selected coach in the view
    ]);
}

### View Update
In your Blade view (`content/admin/support/index.blade.php`), add a form for selecting a coach and submitting the search query:

<form method="GET" action="{{ route('admin.support.index') }}">
    <div class="form-group">
        <label for="coach_id">Filter by Coach</label>
        <select name="coach_id" id="coach_id" class="form-control">
            <option value="">All Coaches</option>
            @foreach($coachs as $coach)
                <option value="{{ $coach->id }}" {{ request('coach_id') == $coach->id ? 'selected' : '' }}>
                    {{ $coach->name }}
                </option>
            @endforeach
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Search</button>
</form>

### Pagination Maintenance
Ensure that the pagination links maintain the `coach_id` filter:

{{ $supports->appends(request()->query())->links() }}

### Explanation
1. **Controller**:
– Use a query builder to conditionally add a filter for `coach_id` if provided.
– Include the selected `coach_id` in the data passed to the view to keep the dropdown state.

2. **View**:
– Add a form with a dropdown to select a coach. Use the `request('coach_id')` helper to pre-select the current filter.
– Append query parameters to pagination links to maintain the current filter.

This will allow you to search for supports by coach ID and paginate the results while preserving the selected filter.

Leave a Comment

Your email address will not be published. Required fields are marked *