Laravel Tutorial #8: Search

Please note that this post may contain affiliate links, and for every purchase you make, at no extra cost to you, a commission fee will be rewarded to me.

The search function is a fundamental feature for almost all websites, and in this article, we’ll talk about how to implement basic search in our Laravel project.

A search function consists of three parts, a search form that allows users to pass queries to the back end, a piece of code that does the search, and a view that displays the results of the search.

Search Form

Let’s first look at the search form. For our template, the search form is located at sidebar.blade.php

    <!-- Search Widget -->
    <div class="card my-4">
        <h5 class="card-header">Search</h5>
        <form class="card-body" action="/search" method="GET" role="search">
            {{ csrf_field() }}
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search for..." name="q">
                <span class="input-group-btn">
            <button class="btn btn-secondary" type="submit">Go!</button>
          </span>
            </div>
        </form>
    </div>

Line 5, adds the CSRF protection to the field.

Line 7, adds name attribute to the input field, its value could be anything, here we’ll call it q.

When the button is clicked, it’ll go to /search, so we need to register the corresponding router.

Route::get('/search', [PostController::class, 'search']);

This route points to the search() method in the PostController.

Search Method

Now, it’s time for us to add the search() method in the PostController.

    public function search(Request $request)
    {
        //get the general information about the website
        $website = General::query()->firstOrFail();

        $key = trim($request->get('q'));

        $posts = Post::query()
            ->where('title', 'like', "%{$key}%")
            ->orWhere('content', 'like', "%{$key}%")
            ->orderBy('created_at', 'desc')
            ->get();

        //get all the categories
        $categories = Category::all();

        //get all the tags
        $tags = Tag::all();

        //get the recent 5 posts
        $recent_posts = Post::query()
            ->where('is_published', true)
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();

        return view('search', [
            'website' => $website,
            'key' => $key,
            'posts' => $posts,
            'categories' => $categories,
            'tags' => $tags,
            'recent_posts' => $recent_posts
        ]);
    }

Line 9, the like here is an operator. Laravel will find the title that is similar to the query that was sent from the user.

Search View

@extends('master')

@section('meta')
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="{{$website['description']}}">
    <meta name="author" content="Eric Hu">
@endsection

@section('title')
    <title>{{$website['website_title']}}</title>
@endsection

@section('content')
    <div class="row">
        <!-- Blog Entries Column -->
        <div class="col-md-8">

            <h1 class="my-4">Search Result For:
                <small>{{$key}}</small>
            </h1>

            @include('vendor.posts-list')

        </div>
        @include('vendor.sidebar')
    </div>
@endsection

Tags:

Leave a Reply

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