Build a live search feature with Laravel and Vue.js
You will need the Laravel CLI installed on your machine. This tutorial was created with Laravel 5.7.
Introduction
Today we’ll be creating a realtime search engine. Realtime means that our users will get updates as soon as they occur. So using our application, our users can search data and get results instantly. We’ll be using Laravel for the backend part, Vue.js for creating our dynamic user interface and Pusher Channels to get realtime updates.
Prerequisites
In order to follow this tutorial a basic or good understanding of Vue.js and Laravel is required, as we’ll be using these technologies throughout this tutorial. Also ensure you have npm or Yarn on your machine.
We’ll be using these tools to build our application:
- Pusher
- Laravel 5.7
- Vue.js
- Vuex
- Laravel CLI installed on your machine
Here’s a demo of the final product:
Pusher setup
Head over to the Pusher website and sign up for a free account. Select Create new app on the sidebar, and hit Create my app to create a new app after filling the form.
Once your app is created, retrieve your credentials from the API Keys tab, and make note of it as we’ll use them later in the tutorial.
Initializing the project and installing dependencies
To get started we’ll install a new Laravel application using the Laravel CLI. We’ll run the following command:
laravel new realtime_search_pusher
Once the installation is finished run the following command to move to your app directory:
cd realtime_search_pusher.
Now we’ll install our node dependencies, first paste this in your package.json
file:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
"axios": "^0.18",
"bootstrap": "^4.0.0",
"cross-env": "^5.1",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.5",
"popper.js": "^1.12",
"vue": "^2.5.7",
"vuex": "^3.0.1",
"laravel-echo": "^1.4.0",
"pusher-js": "^4.2.2"
}
}
Then run npm install
or yarn
to install the dependencies. It’s up to you.
After this step, add the following to your .env
file in the root of your project directory. Ensure to replace the placeholders with your keys from Pusher.
PUSHER_APP_ID=YOUR_PUSHER_APP_ID
PUSHER_APP_KEY=YOUR_PUSHER_APP_KEY
PUSHER_APP_SECRET=YOUR_PUSHER_APP_SECRET
PUSHER_APP_CLUSTER=YOUR_PUSHER_APP_CLUSTER
Database setup
In this tutorial we’ll use SQLite as our database. Create a database.sqlite file in the database directory, and amend the .env file like this:
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
Refer to this section on Laravel website for more relevant information.
Building models and seeding our database
Now, let’s build our database structure. We’ll use again Laravel CLI for that.
Run this command:
php artisan make:model Product -mc
The above command will generate the Product model as well as its migration and its controller ProductController.php
for us.
Open your Product.php
file and paste this:
//realtime_search_pusher/app/Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
//
protected $fillable = ['name', 'description', 'price', 'image'];
}
Next copy and paste this piece of code in your product migration file:
//realtime_search_pusher/database/migrations/*_create_products_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('price');
$table->string('image');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Then run php artisan migrate
to run the migration.
Now, we’ll seed our database to avoid having to populate it manually because it can be tedious.
Execute this command php artisan make:factory ProductFactory
to generate a factory for our Product model. Next copy and paste the following code inside our ProductFactory.php
file
//realtime_search_pusher/database/factories/ProductFactory.php
<?php
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'name'=> $faker->name,
'price' => $faker->numberBetween(25, 850),
'description' => $faker->text(100),
'image' => $faker->imageUrl(850, 640, 'food',true),
//
];
});
Our ProductFactory.php
sets a value for each of our Product model field as you can see in the above code.
The last step in this section is to tell Laravel to use our ProductFactory
. Let’s do that, paste this code inside your DatabaseSeeder.php
file:
//realtime_search_pusher/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
factory(App\Product::class, 25)->create();
}
}
We generate 25 instances of our Product model. Finally run this command so that Laravel can seed the database with the factory we define: php artisan db:seed
.
If you check your database, you can see that your database has been populated as well and it contains 25 rows. Great isn’t it!
Defining routes and creating the ProductController
In this section we’ll define our app endpoints and define the logic behind our ProductController.php
.
Let’s create a get
route named search
(which will be called when the user attempts to search for products), and another get
route named products
to fetch our products from database. Paste the following into api.php
:
//realtime_search_pusher/routes/api.php
use Illuminate\Support\Facades\Route;
Route::get('search','ProductController@search');
Route::get('products','ProductController@get');
We should also define a get route named /
to return our app view. Copy this code and replace the existing one inside your web.php
file:
//realtime_search_pusher/routes/web.php
Route::get('/', function () {
return view('search');
});
Now let’s define our controller logic. Our controller functions will be responsible for actions to handle when some requests reach our API endpoints.
Open your ProductController
file and paste the following code:
//realtime_search_pusher/app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use App\Events\SearchEvent;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
//
public function search(Request $request)
{
$query = $request->query('query');
$products = Product::where('name', 'like', '%' . $query . '%')
->orWhere('description', 'like', '%' . $query . '%')
->get();
//broadcast search results with Pusher channels
event(new SearchEvent($products));
return response()->json("ok");
}
//fetch all products
public function get(Request $request)
{
$products = Product::all();
return response()->json($products);
}
}
In the above code we have two functions get
and search
:
get
- this function returns all existing posts in our databasesearch
- this function is a bit tricky. It gets the query sent in the request and returns every product whose name or description contains it. This is handled there:
Product::where('name', 'like', '%' . $query . '%')
->orWhere('description', 'like', '%' . $query . '%')
Emit event
Well you may have noticed this line: event(new SearchEvent($products))
. What is its purpose?
It broadcasts an event with search results to the client-side of our app using Laravel broadcasting. We’ll see how to create this event in the next part of the tutorial.
Create a search event with broadcasting
Broadcast is a fancy way to say emit.
Our SearchEvent
event will be emitted whenever the user searches for a product or initiates a search. Enough talk , let’s focus on the code. Let’s create our SearchEvent
by running the following command in your terminal: php artisan make:event SearchEvent
.
Now open your SearchEvent
file and paste the following:
//realtime_search_pusher/app/Events/SearchEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class SearchEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $products;
public function __construct($products)
{
//
$this->products = $products;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
/**
* @return string
*/
public function broadcastAs()
{
return 'searchResults';
}
public function broadcastOn()
{
return new Channel('search');
}
}
Our class constructor initializes a set of products that are nothing but the search results from the database. We have two additional functions that may seem strange to you:
broadcastAs
: customizes the broadcast name because by default Laravel uses the event’s class name.broadcastOn
: defines the channelsearch
(which we’ll set up further on the tutorial) on which our event should be broadcast.
Broadcasting configuration
According to Laravel documentation about event broadcasting, before broadcasting any events, you will first need to register the App\Providers\BroadcastServiceProvider
. In fresh Laravel applications, you only need to uncomment this provider in the providers
array of your ../config/app.php
configuration file. This provider will allow you to register the broadcast authorization routes and callbacks.
If this is done, you have to tell Laravel to use Pusher to broadcast events. Open your .env
file and ensure you have this line: *BROADCAST_DRIVER*``=pusher
As we are broadcasting our events over Pusher, we should install the Pusher PHP SDK using the Composer package manager:
composer require pusher/pusher-php-server "~3.0"
Setting up the broadcast channel
Laravel broadcasts events on well defined channels. As said above our event should be broadcast on search
channel. It’s time to set it up. Paste the following code in your channels.php
file:
//realtime_search_pusher/routes/channels.php
Broadcast::channel('search', function () {
return true;
});
As we aren’t using Laravel auth, we return true
in the function callback so that everybody can use this channel to broadcast events.
Set up Laravel Echo
We’ll use Laravel Echo to consume our events on the client-side.
Open your resources/js/bootstrap.js
file and uncomment this section of the code:
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: false
});
The above code sets up Laravel Echo with Pusher. This will make our app aware of events broadcasted, and Laravel Echo will consume our events
Our app is ready to broadcast and consume events in realtime using Pusher channels. Let’s focus now on the frontend of your app.
Set up Vuex store
We’ll be using the Vuex library to centralize our data and control the way it is mutated throughout our application.
Create our state
Vuex state is a single object that contains all our application data. So let’s create ../resources/js/store/state.js
and paste this code inside:
let state = {
products: []
}
export default state
The code above is straightforward. The products
key is an array responsible to store our database products
Create our getters
With help of getters we can compute derived based on our data store state. Create ../resources/js/store/getters.js
and paste this code inside
let getters = {
products: state => {
return state.products
}
}
export default getters
Create our mutations
Mutations allow us to perform some changes on our data. Create ../resources/js/store/mutations.js
and paste this piece of code inside:
let mutations = {
SET_PRODUCTS(state, products) {
state.products = products
}
}
export default mutations
Our mutations object has a SET_PRODUCTS
function with two arguments state
and products
; this function assigns the products
array to our state products key.
Create our actions
Vuex actions allow us to perform asynchronous operations over our data. Create the file ../resources/js/store/actions.js
and paste the following code:
let actions = {
SEARCH_PRODUCTS({commit}, query) {
let params = {
query
};
axios.get(`/api/search`, {params})
.then(res => {
if (res.data === 'ok')
console.log('request sent successfully')
}).catch(err => {
console.log(err)
})
},
GET_PRODUCTS({commit}) {
axios.get('/api/products')
.then(res => {
{
commit('SET_PRODUCTS', res.data)
}
})
.catch(err => {
console.log(err)
})
}
}
export default actions
We have defined two actions and each of them responsible of a single operation, either products search or products search. They both perform asynchronous calls to our API routes.
-
SEARCH_PRODUCTS
sends a get request to our/api/search
endpoint to get products. This action is dispatched whenever the user is searching for something. -
GET_PRODUCTS
makes a get request to ourapi/products
endpoint to get our database products and commits the request result withSET_PRODUCTS
mutation.
Set up our store with Vue
Create the file ../resources/js/store/index.js
and paste this code inside:
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
import state from "./state";
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
getters,
actions
})
Then, we export our store and add it to the Vue instance. Add this code to your ../resouces/js/app.js
file.
require('./bootstrap');
window.Vue = require('vue');
import store from './store/index'
Vue.component('searchbar', require('./components/Searchbar'));
Vue.component('product', require('./components/Product'))
Vue.component('products', require('./components/Products'))
const app = new Vue({
el: '#app',
store
});
The previous code also globally registers three Vue components, Searchbar.vue
,Product.vue
and Products.vue
that we’ll build in the next part of this tutorial.
Building Vue components
We’ll build three Vue components for our app, a Searchbar
component, a Product
component and a Products
component, each of them responsible for a single functionality.
Create the Product.vue component
The Product.vue
component is responsible for encapsulating details about a single product instance from the database and rendering it in a proper and styled way.
Paste the following inside your Product.vue
component.
//../resources/js/components/Product.vue
<template>
<div class="card">
<img class="card-img-top" :src="product.image" :alt="product.name">
<div class="card-body">
<h5 class="card-title">{{product.name}}</h5>
<p class="card-text">{{product.description}}</p>
<span class="text-danger font-weight-bold">${{product.price}}</span>
</div>
</div>
</template>
<script>
export default {
name: "Product",
props: ['product']
}
</script>
<style scoped>
.card {
cursor: pointer;
margin-bottom: 8px;
}
</style>
Our Product.vue
component takes a product
property whose details we render in the component body. This code is straightforward as you may have noticed it. We are using the Bootstrap framework to style our component.
Create the Products.vue component
This component will render products items from database. It’s that simple.
So create your Products.vue
component and paste this code inside:
//../resources/js/components/Products.vue
<template>
<div class="container">
<div class="row" v-for="products in groupedProducts">
<div class="col-md-3 col-sm-6" v-for="product in products">
<product class="animated fadeIn" :product="product"></product>
</div>
<div class="col w-100"></div>
</div>
</div>
</template>
<script>
import {mapGetters} from 'vuex'
import product from '../components/Product'
export default {
name: "Products",
components: {
product
},
mounted() {
this.$store.dispatch('GET_PRODUCTS')
window.Echo.channel('search')
.listen('.searchResults', (e) => {
this.$store.commit('SET_PRODUCTS', e.products)
})
},
computed: {
groupedProducts() {
return _.chunk(this.products, 4);
},
...mapGetters([
'products'
])
}
}
</script>
This component has a groupedProducts
computed property which splits our products array and makes group of six.
In the mounted
hook function we dispatch the GET_PRODUCTS
action, and we use Vuex helper function …mapGetters()
to access our products state.
We also use the Echo library here to listen to events.
window.Echo.channel('search')
.listen('.searchResults', (e) => {
this.$store.commit('SET_PRODUCTS', e.products)
console.log(e)
})
We first subscribe to search
channel, then we listen to the searchResults
event triggered when the user searches for something. Then we commit SET_PRODUCTS
mutation with the event payload. Yes it’s that simple.
Note: You must append a dot to the event name so Laravel Echo can listen to your event.
Otherwise you won’t be able to listen to any event.
Create our Searchbar.vue component
This component contains the input field with a search Button. Whenever the user enters their search query inside the input field, we’ll make a request to our backend to get realtime results.
Copy and paste the following code in your Searchbar.vue
component:
<template>
<div class="container">
<div class="input-group mb-3">
<input v-model="query" type="text" class="form-control" placeholder="Product name or description"
aria-label="Product name or description"
aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" @click="searchProducts" @keyup.enter="searchProducts" type="button">
Search
</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Searchbar",
data() {
return {
query: '',
}
},
watch: {
query: {
handler: _.debounce(function () {
this.searchProducts()
}, 100)
}
},
methods: {
searchProducts() {
this.$store.dispatch('SEARCH_PRODUCTS', this.query)
}
}
}
</script>
<style scoped>
</style>
We bind the query
data to our input field using Vue.js v-model
, and we watch it. Whenever the query data changes we wait 100 ms and dispatch SEARCH_PRODUCTS
action. This is what the following code is doing:
query: {
handler: _.debounce(function () {
this.searchProducts()
}, 100)
}
Finalize the app
Now, let’s create our search.blade.php
file which contains our three Vue components. Paste this code inside:
//../resources/views/search.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
{{--bxslider--}}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css"/>
<link rel="stylesheet" href="{{mix('css/app.css')}}">
<title>Realtime search engine with Pusher and Laravel</title>
</head>
<body>
<div id="app">
<div class="container">
<h5 class="text-center" style="margin-top: 32px">Realtime search engine with Laravel and Pusher</h5>
<br><br>
<searchbar></searchbar>
<products></products>
</div>
</div>
<script async src="{{mix('js/app.js')}}"></script>
</body>
</html>
We are almost done. Now open your terminal and run npm run dev
to build your app in a proper way. This can take a few seconds. After this step run php artisan serve
and open your browser at localhost:8000
to see your app working fine. Now try searching a product name or its description in the searchbar, you should get realtime results for your search. You are now a boss 😎
Note: If you encounter a 500 error when trying to search, it’s possible that you have to disable Pusher encryption. Open these files
../config/broadcasting.php
and../resources/js/bootstrap.js
and make sure you disable Pusher encryptionencrypted: false
in both of them.
Conclusion
In this tutorial we’ve created a realtime search engine using Laravel, Vue.js, and Pusher to provide realtime functionality. You can think up new ideas to extend the application. It’ll be fun to see what you come up with. The source code for this tutorial is available on GitHub here.
3 October 2018
by Ethiel Adiassa