Creation Search Engine on Laravel sites using Solr

Teguh Arief

Sep 24, 2020

Share article to

Illustration of creation search engine.

Search engine has become a useful tool in today's internet world. Solr enables you to easily create search engines which searches databases. In this article I will show you how easy it is to implement Solr and its bridge the PHP Solarium library in the Laravel framework.

Solr configuration



config/solr.php


[
'localhost' => [
'host' => env('SOLR_HOST', '192.168.99.100'),
'port' => env('SOLR_PORT', '8983'),
#'path' => env('SOLR_PATH', '/solr/'),
'core' => env('SOLR_CORE', 'mycore')
]
]
];


Install the PHP Solarium library




composer require solarium/solarium


Boot up the Solarium Client


php artisan make:provider SolariumServiceProvider


Edit app/Providers/SolariumServiceProvider.php


app->bind(Client::class, function ($app) {
return new Client($app['config']['solr']);
});
}

public function provides()
{
return [Client::class];
}
}


Now open up the file app/config/app.php and add the new SolariumServiceProvider to the other application providers


return [
'providers' => [
// List off others providers...
App\Providers\SolariumServiceProvider::class,
]
];


The integration




php artisan make:controller SolariumController


Add the Controller to the file app/Http/Controllers/SolariumController.php


client = $client;
}

public function search()
{
$input = Input::get('q');
$query = $this->client->createSelect();
$query->setQuery('*:*');
$query->setQuery('name:"' . $input . '"');
$query->setStart(0);
$query->setRows(10);
$resultset = $this->client->select($query);

return view('search', compact('resultset'));

}
}


Add the View to the file resources/views/search.blade.php


  @if (count($resultset) > 0)
@foreach ($resultset as $data)
{{ $data->name }}
@endforeach
@else
Data Not Found.
@endif


Now add the search router to routes file. You can find the routes file at the default location app/Http/routes.php


Route::get('/search', 'SolariumController@search');