Simple and Advanced Search in Laravel​ 8

Simple and Advanced Search in Laravel​ 8

 

Simple and Advanced Search in Laravel 8


After we inserted data into our table, we displayed those entries on the browser. Just in case we have hundreds and thousands of records, we need to include a search form for faster retrieval of data.

In this tutorial, I have made two options for simple and advanced searches in Laravel. If you only have one search box, you may need the simple search box, if it’s more than one, you might be needing of the advanced feature. Take a look at the guide below.


Search Features

Simple Search
– Search the record of people containing the name

Advanced Search
– Name of Person
– Contains an address
– Range of an age

Let’s get started


1. Install Laravel

Open your terminal and download the Laravel Framework by executing the command.

composer create-project --prefer-dist laravel/laravel larasearch

It takes a few minutes to download. Now, go into the research directory.

 cd larasearch 

After that, start your server.

php artisan serve

Open your browser and go to http://localhost:8000

2. Configure your .env file

Make sure to configure your .env according to your settings.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=searchdb
DB_USERNAME=root
DB_PASSWORD=

3. Model and Migration

Let’s create a model and migration and the same time. Open your terminal and execute the command below.

 php artisan make:model People -m 

Database Schema

Navigate to database » migrations » create_people_table.php and add additional fields.

public function up()
{
    Schema::create('people', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('address');
    $table->integer('age');
    $table->timestamps();
    });
}

Next, go to the App » Providers » AppServiceProvider.php

use Illuminate\Support\Facades\Schema;
.
.
public function boot()
{
    Schema::defaultStringLength(191);
}

Then, execute the migration.

php artisan migrate

After that, add fields as fillable. Go to App  » People.php

protected $fillable = ['name', 'address', 'age']; 

4. Populate the People table with data

You can populate data manually so that it will display on your search. But in this tutorial, let’s use the Laravel factory feature to insert data automatically.

php artisan make:factory Peoplefactory 

Go to database >> factories >> Peoplefactory.php and set the fields to be populated.

$factory->define(App\People::class, function (Faker $faker) {
    return [
        'name'    => $faker->name,
        'address' => $faker->address,
        'age'     => mt_rand(18, 150),
    ];
});

Notice that I added  mt_rand(18, 150). It automatically adds the age between 18 to 150. Then, let’s execute the faker using an artisan tinker.

php artisan tinker
>> factory(App\People::class, 50)->create(); 

The command above will insert 50 records into your people table. You can now check your table to confirm if data has been successfully inserted.

5. Create Controller

Now, it’s time for us to create the controller of our search form. Execute the command below the generate a SearchController.

php artisan make:controller SearchController 

After that, go to app >> Http >> Controllers >> SearchController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
    public function index()
    {
        $data = \DB::table('people')->paginate(10);
        return view('search', compact('data'));
    }
    public function simple(Request $request)
    {
        $data = \DB::table('people');
        if( $request->input('search')){
            $data = $data->where('name', 'LIKE', "%" . $request->search . "%");
        }
        $data = $data->paginate(10);
        return view('search', compact('data'));
    }
    public function advance(Request $request)
    {
        $data = \DB::table('people');
        if( $request->name){
            $data = $data->where('name', 'LIKE', "%" . $request->name . "%");
        }
        if( $request->address){
            $data = $data->where('address', 'LIKE', "%" . $request->address . "%");
        }
        if( $request->min_age && $request->max_age ){
            $data = $data->where('age', '>=', $request->min_age)
                         ->where('age', '<=', $request->max_age);
        }
        $data = $data->paginate(10);
        return view('search', compact('data'));
    }
}

6. Configure your Routing

Now, we have to set the routing of our application.

Route::get('/people', 'SearchController@index');
Route::get('/people/simple', 'SearchController@simple')->name('simple_search');
Route::get('/people/advance', 'SearchController@advance')->name('advance_search');

7. Create a blade for the search

Lastly, we need to display the data in our view.

From your resources folder, create search.blade.php and copy the codes below.

<!DOCTYPE html>
<html>
<head>
<title>Laravel Search</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-4">
                <h3>Simple Search</h3><br>
                <form action="{{ route('simple_search') }}" method="GET">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" placeholder="Type the name" aria-describedby="basic-addon2" name="search">
                        <div class="input-group-append">
                            <button class="btn btn-secondary" type="submit">Search</button>
                        </div>
                    </div>
                </form>
                <form action="{{ route('advance_search') }}" method="GET">
                    <h3>Advanced Search</h3><br>
                    <input type="text" name="name" class="form-control" placeholder="Person's name"><br>
                    <input type="text" name="address" class="form-control" placeholder="Address"><br>
                    <label>Range of Age</label>
                    <div class="input-group">
                        <input type="text" name="min_age" class="form-control" placeholder="Start Age">
                        <input type="text" name="max_age" class="form-control" placeholder="End of Age">
                    </div><br>                    <input type="submit" value="Search" class="btn btn-secondary">                </form>
            </div>
            <div class="col-md-8">
                <h3>List of People</h3>
                <table class="table table-striped">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Age</th>
                    </tr>
                    @foreach($data as $pep)
                    <tr>
                        <td>{{ $pep->id }}</td>
                        <td>{{ $pep->name }}</td>
                        <td>{{ $pep->address }}</td>
                        <td>{{ $pep->age }}</td>
                    </tr>
                    @endforeach
                </table>
                {{ $data->appends(request()->except('page'))->links() }}
            </div>
        </div>
    </div>
</body>
</html>

Notice that I added a pagination using {{ $data->appends(request()->except('page'))->links() }}. This code is necessary to include the query string whenever the user clicks the pagination link.

And that’s all.

If you have a question, don’t hesitate to ask a question below.

Reactions

Post a Comment

4 Comments

CAN FEEDBACK

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)

close