Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eddy1992's avatar

How does a search bar works ?

Hi I am still learning can anybody help me with the logic of search bar . I have a search bar in my view but I dont know how will use it .

Thank You

0 likes
2 replies
bobbybouwmann's avatar
Level 88

Well it works just like a form. You post the data to the form and then based on that you show the results

First we need to create a route to be able to search (app/Http/routes.php)

Route::post('search', ['as' => 'search', 'uses' => 'SearchController@index']);

Now we need to create a few that can search for us (resources/views/search.blade.php). You need to include this view in your header or wherever you want to show this

{!! Form::open(['route' => 'search']) !!}

{!! Form::text('query') !!}
{!! Form::submit('Search') !!}

{!! Form::close() !!}

Next we need the controller for the functionality (app/Http/Controllers/SearchController.php). As an example I added the results for pages and posts but you can do with it whatever you want

use Illuminate\Http\Request;
use App\Post;
use App\Page;

class SearchController extends Controller {

    public function index(Request $request)
    {
        $query = $request->get('query');

        $pages = Page::where('title', 'LIKE', "%$query%")->get();

        $posts = Posts::where('title', 'LIKE', "%$query%")
                    ->orWhere('body', 'LIKE', "%$query%")
                    ->get();

        return view('results', compact('pages', 'posts');
    }   

}

Finally to display the results (resources/views/results.blade.php)

<h1>Search results</h1>

@if (count($pages)

    <h3>Pages:</h3>     

    <ul>

        @foreach($pages as $page)
            
            <li>{!! link_to_route('pages.show', $page->title, $page->id) !!}</li>

        @endforeach 

    </ul>

@endif

@if (count($posts)

    <h3>Posts:</h3> 

    <ul>

        @foreach($posts as $post)
            
            <li>{!! link_to_route('posts.show', $post->title, $post->id) !!}</li>

        @endforeach 

    </ul>

@endif

Note: this is far from perfect but it will do what you need ;) If you want to go a step further you can take a look at the search essentials: https://laracasts.com/lessons/search-essentials

2 likes

Please or to participate in this conversation.