Laravel and Vue collaborate for an intelligently designed autocomplete feature

Currently, I am troubleshooting an issue with a vue autocomplete feature on a laravel website.

I have configured the route, controller, and blade. When I inspect the vue component and type in the input field, I can see the keywords I am typing in the console, indicating that it is capturing the input correctly.

When I dump the $groupResult variable in my controller, I get about 100 results as expected. My goal is to implement an autocomplete feature on the input field that searches within these 100 results.

What am I overlooking here?

Route:

Route::get('campaigns/categories','CampaignsController@searchcategories')->name('campaigns.categories');

Controller:

public function searchcategories(Request $request)
{
    $userNum = $this->user;
    $category = new categoryService();
    $safecategories = $category->info($userNum);

    $groupResult = array();

    foreach($safecategories->categories as $categories){
        $groupItem = array();
        $groupItem["group_code"] = $categories->group_code;
        $groupItem["group_name"] = $categories->group_name;

        array_push($groupResult, $groupItem);
    }

     return view('campaigns')
        ->with('groupResult', $groupResult);

}

Blade Template:

<div id="categoryNames">
<input type="text" v-model="keywords">
<ul v-if="results.length > 0">
  <li v-for="result in results" :key="result.id" v-text="result.name"></li>
</ul>
</div>

var categoryNames = new Vue({
  data() {
    return {
      keywords: null,
      results: []
    };
  },

  watch: {
    keywords(after, before) {
      this.fetch();
    }
  },

  methods: {
    fetch() {
      axios.get('campaigns/categories', { params: { keywords: this.keywords } })
        .then(response => this.results = response.data)
        .catch(error => {});
    }
  }
}).$mount('#categoryNames');

Answer №1

When filtering existing results, there's no need to make a server call for this task.

<div id="categoryNames">
<input type="text" v-model="keywords">
<ul v-if="filteredResults.length > 0">
  <li v-for="result in filteredResults" :key="result.id" v-text="result.name"></li>
</ul>
</div>

var categoryNames = new Vue({
  data() {
    return {
      keywords: null,
      results: []
    };
  },

  computed: {
    filteredResults () {
      return this.keywords ? this.results.filter(row => row.name.search(new RegExp(`${this.keywords}`, 'i')) !== -1) : this.results
    }
  }
}).$mount('#categoryNames');

The computed property retrieves an array of objects based on the object key name for filtering. It utilizes regex for case-insensitive searching when a keyword is present. Without a keyword, it returns the entire results object.

Note: This code was not directly tested, so please watch out for any potential typos. However, I have successfully implemented similar versions in large-scale applications before.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the picture dynamically when hovering

Is there a way to change an image randomly when hovering over it? The hover effect is working fine, but the image does not revert back when the mouse moves out. Any suggestions on how to fix this? var arr = ["020", "053", "306", "035", "930"]; function ...

Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button. The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

Finding the length of a filter in an AngularJS directive

I'm trying to figure out how to retrieve the value of filtered.length within my custom directive called my-dir. <li my-dir ng-repeat="result in filtered = (results | filter:query | orderBy: 'title')"> <h1>{{ result.title }}& ...

Translate unknown provider in Angular using $translateProvider

Here is the situation I am facing: I am working on an Ionic project and I want to implement internationalization using angular-translate. To achieve this, I have added angular-translate.min.js to my project: <script src="lib/ionic/js/ionic.bundle.js"&g ...

Improprove the design of the dropdown component using React

One of the challenges I am facing in my project is using multiple dropdowns from semantic-ui-react. Each dropdown needs to have different props, making the code look like this: <div className="wrapper"> <img className="icon" src={iconA} ...

Encountered an issue with Laravel 5.8 and React Native when trying to listen to a private channel with Pusher. The error states "No callbacks on conversations34 for pusher

Encountering an issue when the app developer attempts to listen to events via a pusher private channel. Below is the Laravel code snippet showcasing the problem. routes/api.php Route::middleware('auth:api')->post('/broadcast/auth', ...

Retrieve information from D3 line interpolation functions

I'm currently working on creating a D3 graph that features a shaded area in the middle. The top part of the shaded region aligns with the line graph. For reference, the data structure I'm using is as follows: line = [ {x: 0, y:1}, {x: 1, y: ...

Ensure that variables are accessible to asynchronous calls without the use of closures

As a newcomer to the world of javascript, I've been trying to navigate the realm of nested functions. Let's explore the following two examples: // example 1 var x = 45; function apple(){ var y = 60; setTimeout(function(){ console ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

There seems to be a JSON syntax error on the website for tracking Covid-

Hi everyone, I'm currently working on a Covid-19 tracker website and facing an issue that says: 'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' ; Being new to web development, I am unsure about what&apo ...

HTML5 Dragend event failed to trigger in Firefox

While working on my project, I encountered an issue where the 'dragend' event is not fired in Firefox 22.0 on Ubuntu but works perfectly fine in Chrome. I have written a logic to make changes on drag start and revert them if drop fails, triggered ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

Find the smallest number within an array without relying on the Math function

Could someone assist me in creating a function that finds the lowest number in an array? I've been struggling with this and previous answers on similar questions didn't really help as they presented solutions with unfamiliar code. The current cod ...

Customize Bootstrap Vue dropdown without any predefined styling options

After reviewing the documentation, I created a sample example utilizing the b-dropdown component: You can view the example here: https://codesandbox.io/s/6lhk6?file=/src/components/GenericItem.vue However, when I implemented the component in the code: &l ...

Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout: HTML & ...

Alert: Attempting to invoke the setState method on an unmounted component

While running unit tests with Jest, I encountered a warning when attempting to change the setState input value. The warning message says: "Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in you ...

Animating fjdxsu using Threejs formula

Can you provide me with the exact formula that should be used in the animate function? ...

Getting the value of a field in a Firestore document

I've encountered an issue while trying to assign the field artName to my "documents". Despite populating id and url successfully, the documents.push() method seems to be ignoring doc.artName. Strangely, when I console.log doc.data(), the assigned valu ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...