user6780526
user6780526

Reputation:

Search in vuejs with laravel backend api

I'm using laravel 5.6 as the api for the backend and vuejs for the frontend spa application. And https://github.com/nicolaslopezj/searchable package for search which worked well in my previous projects where i used blade templating engine.

I'm new to vuejs and im learning how to do things and im stuck at a point where im confused how to use laravel search on the frontend.

What i did previously in other projects where i used blade for the frontend

In my controller

public function index(Request $request)
    {
        $start_search = microtime('s');
        $searchterm = $request->input('search');
        if($request->has('search')){
           $results =  Web::search($searchterm)->paginate(10);
         } else {
          $results =  Web::latest()->paginate(10);
         }
        $stop_search = microtime('s');
        $time_search = ($stop_search - $start_search);
        return view('search.index', compact('results', 'searchterm', 'time_search'));
    }

And in my view

<small>{{$results->total()}} results found for "<em class="b-b b-warning">{{$searchterm}}</em>" in {{$time_search}} seconds</small>
@forelse ($results as $result)
        <div class="mb-3">
          <a href="{{ url($result->url) }}" class="text-primary clear h-1x">{{$result->meta_title}} <span class="badge badge-pill primary">{{$result->rank}}</span></a>
          <span class="text-success clear h-1x">{{$result->url}}</span>
          <span class="h-2x">{{$result->meta_description}}</span>
        </div>
      @empty
        No Results Found
      @endforelse
      <div class="pt-2 pagination-sm">
          {{ $results->links('vendor.pagination.bootstrap-4') }}
      </div>

This code worked well where i was able to search and display results properly along with search time.

Now i want to do the same with laravel api and vuejs frontend. So this is what i tried

public function index(Request $request)
        {
            $start_search = microtime('s');
            $searchterm = $request->input('search');
            if($request->has('search')){
               $results =  Web::search($searchterm)->paginate(10);
             } else {
              $results =  Web::latest()->paginate(10);
             }
            $stop_search = microtime('s');
            $time_search = ($stop_search - $start_search);
            return WebResource::collection($results);
        }

I created a collection resource for the same.

Question 1. My question related to controller code, how to return $searchterm and $time_search so that i can use them on the frontend.

In my vue component, i tried with my learning till now

<template>
other code..
<div class="mb-3" v-for="result in results" :key="result.results">
  <router-link :to="result.url" class="text-primary clear h-1x"> {{ result.meta_title }} </router-link>
  <span class="h-2x">{{ result.meta_description }}</span>
</div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'

export default {
  layout: 'main',

  computed: mapGetters({
      locale: 'lang/locale',
      authenticated: 'auth/check'
  }),

  metaInfo () {
    return { title: this.$t('searchpagetitle') }
  },

  data: function () {
    return {
        results: [],
        title: window.config.appName
    }
  },

  watch: {
    locale: function (newLocale, oldLocale) {
      this.getResults()
    }
  },

  mounted() {
      console.log(this.locale)
      this.getResults ()
  },

  methods: {
    getResults() {
      var app = this;
      axios.get('/api/web')
        .then(response => {
          // JSON responses are automatically parsed.
          this.results = response.data.data
        })
        .catch(e => {
          this.errors.push(e)
        })
    }
  }
}
</script>

Question 2: My second question related to vuejs, how to create a search form and render results according to the search and with proper search url ending with ?searchterm=searchkeywords in my case.

When i used blade i used the normal html form with action url so that it rendered results. Also i used $searchterm to use the same search terms to search in other routes like images, videos. I just used {{ url('/images?searchterm='.$searchterm) }} in the href so that when user clicks on it, it renders results of all images with the same keyword just like google. And also used placeholder as "enter your search" and value as "{{$searchterm}}" so that the search term stayed in the search form too.

I want to know how to do all the same in vuejs.

Thank you

Upvotes: 2

Views: 2444

Answers (1)

chohan
chohan

Reputation: 58

It is better to append the search keyword in request URL of API in frontend. So your request url will be like

axios.get('/api/web?searchterm='+this.searchterm)

And in your Laravel controller, you can get this value by using Input::get() , so your code to get searchterm will be

$searchterm = Input::get('searchterm');

And then you can fetch your data on basis of $searchterm variable.

Upvotes: 1

Related Questions