DEV Community

loading...
Cover image for Laravel 8 Tutorial #8: Search

Laravel 8 Tutorial #8: Search

Eric Hu
Blogger, Web Developer
Originally published at techjblog.com Updated on ・2 min read

You can download the source code of this tutorial here: https://www.techjblog.com/index.php/laravel-tutorial-for-beginners/

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>
Enter fullscreen mode Exit fullscreen mode

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']);
Enter fullscreen mode Exit fullscreen mode

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
        ]);
    }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
mohammadfouladgar profile image
Fouladgar.dev

Nice article!

If you wanna have a advanced search, you can use this package:
github.com/mohammad-fouladgar/eloq...
Also, I wrote an article about this topic that you can read here:
dev.to/mohammadfouladgar/making-th...

Collapse
rys0105 profile image
Nesyou

It's a very good solution.
Thank you