Home > Software design >  Displaying everything after search term is deleted
Displaying everything after search term is deleted

Time:11-27

I have a site that displays every post that is stored in a database with a search bar at the top. Obviously when the user first visits the page no search term is applied and all posts are visible.

When the user then searches for a word and presses the search button everything works fine. However, when you delete the string from the search bar and press search again all posts are gone, of course going back with mouse buttons works and reloading aswell. But I would like to achieve that when the empty search bar is submitted all posts appear.

This is the form:

<form action=" {{ route('overview') }}" method="get">
    <div>
        <input placeholder="Schlagwort" type="text" id="s" name="s" value="{{ request()->get('s') }}">
    </div>
    <button type="submit">Suchen</button>
</form>

This is the controller with the search function:


public function index(Request $request) {

    $posts = Post::get();

    if($request->has('s')) {
        $query = strtolower($request->get('s'));
        $posts = $posts->filter(function ($post) use ($query) {
            if (Str::contains(strtolower($post->Titel), $query)) {
                return true;
            }
            return false;
        });

    } 
    return view('posts.overview', ['posts' => $posts]);
}

I tried this when trying to achieve the 'empty search bar display everything "feature" '

public function index(Request $request) {
    $posts = Post::get();

    if($request->has('s')) {
        $query = strtolower($request->get('s'));
        $posts = $posts->filter(function ($post) use ($query) {
            if (Str::contains(strtolower($post->Titel), $query)) {
                return true;
            }
            return false;
        });

    } else if ($request == ' ') {
        return view('posts.overview', ['posts' => $posts]);
    }
    return view('posts.overview', ['posts' => $posts]);
}

As well swapped out with else if ($request == null) ...

CodePudding user response:

You are checking if the s input is present, when instead you want to check if it has a value. Use the filled() method for that.

In addition, you are needlessly fetching everything from the database and then filtering in PHP. Instead, build a query that checks for the input value using the when() method.

public function index(Request $request)
{    
    $posts = Post::query()
        ->when(
            $request->filled('s'),
            fn ($q) => $q->where('title', 'like', $request->s)
        )
        ->get();

    return view('posts.overview', ['posts' => $posts]);
}
  • Related