'how to hide results from database until the seacrh is complete in Laravel?

i am making a search for the website so the user can search for results from database

everything is working fine but how can i hide results until the user complete the search?

this is the controller:

class SearchController extends Controller
{
public function search(Request $request){
    // Get the search value from the request
    $search = $request->input('search');
    

    // Search in the title and body columns from the posts table
    $classes = Classes::query()
        ->where('course_name', 'LIKE', "%{$search}%")
        ->orWhere('course_lecturer', 'LIKE', "%{$search}%")
        ->get();


    // Return the search view with the results compacted
    return view('search', compact('classes'));
}
}

and here is the view:

<div class="container">
<h1>Search</h1>
<form action="{{ route('search') }}" method="GET">
    <input style="font-family: Frutiger" dir="rtl" type="text" placeholder="search" name="search" required/>
    <button style="font-family: Frutiger" class="col-md-12 btn btn-primary" type="submit">Search</button>
</form>  
</div>
@if($classes->isNotEmpty())
@foreach ($classes as $classes)
    <div class="post-list text-center">
        <p>{{ $classes->course_name }}</p>
        <p>{{ $classes->course_lecturer }}</p>
        <a target="_blank" href="{{ $classes->file_link }}"><img src="{{ $classes->file_link }}" href="{{ $classes->file_link }}"  width="150px" height="300px"></a>
        <hr>
        
    </div>
@endforeach
@else 
<div>
    <h2 class="text-center">No posts found</h2>
</div>
@endif

so my problem is the view is showing all the results before the user search and i want results to be hidden until the search is complete

how to achieve that?



Solution 1:[1]

it's because in first load of the page search is null so you're returning all of the database!

You can fix it like this:

class SearchController extends Controller
{
public function search(Request $request){
    // Get the search value from the request
    $search = $request->input('search');
    $classes = [];
    if($search) {
    // Search in the title and body columns from the posts table
        $classes = Classes::query()
            ->where('course_name', 'LIKE', "%{$search}%")
            ->orWhere('course_lecturer', 'LIKE', "%{$search}%")
            ->get();
    }

    // Return the search view with the results compacted
    return view('search', compact('classes'));
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1