Retrieve information by performing a search query on two tables in Laravel and VueJS, using specific conditions

Is there a way to retrieve data from both the Employee and Company tables based on a search by Company name rather than Company Id? These tables have a one-to-many relationship. The current search functionality is working well, but any assistance on implementing this specific search feature would be greatly appreciated.

Here is the code in the EmployeeController:

 public function search(){

       if($search = \Request::get('q')){

             $employees = Employee::where(function($query) use ($search){
                 $companies = Company::Where('id','company_id');
                $searcompany ?????
                foreach($companies AS $company){ 
                     $searcompany = $company->Company;
                }

                $query->Where('BadgeCode','LIKE',"%$search%")              
                 ->orWhere($searcompany,'LIKE',"%$search%")

            })->orderBy('BadgeCode','desc')->paginate(20);
                            // return $users;
        }        else{
           $employees = Employee::latest()->paginate(5);
                     }
         return $employees;

    }

HTML Code in Employee.vue:

<div style="margin-left:450px; margin-top:0px;margin-bottom:-10px;">
              <h3 class="card-title">
                <div class="card-tools">
                  <div class="input-group input-group-sm" style="width: 250px;">
                    <input
                      name="table_search"
                      class="form-control float-right"
                      placeholder="Search"
                      @keyup="searchit"
                      v-model="search"
                      type="search"
                      aria-label="Search"
                    />
                    <div class="input-group-append">
                      <button type="submit" class="btn btn-default" @click="searchit">
                        <i class="fas fa-search"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </h3>
            </div>

Script Code in Employee.vue:

    export default {
    data() {
        return {
employees :{},
     search: "",
    },
        methods: {
            searchit: _.debounce(() => {
              Fire.$emit("searching");
            }, 300),
    },

    created() {
        Fire.$on("searching", () => {
          let query = this.search;
          axios
            .get("api/findemployee?q=" + query)
            .then(data => {
              this.employees = data.data;
            })

            .catch(() => {});
        });
    }
    }

The API Route is:

Route::get('findemployee','API\EmployeeController@search');

Answer №1

This controller method appears to be excessively complex. Consider simplifying it by following this example.

$employees = Employee::with('Company')
    ->when($request->filled('search'), function ($query) use ($request) {
        return $query
           ->where('name', 'like', "%$request->search%")
           ->whereHas('Company', function ($query)  use ($request) {
                return $query->where('name', 'like', "%$request->search%");
            });
    })->paginate(5);

Replace 'q' with the appropriate field name you are searching for.

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

I am currently struggling to make the userID route parameter function correctly with react-router-relay

I've been diving into the world of React Relay and GraphQL with react-relay-router, but I'm having trouble getting the params in my routes to function correctly. Specifically, I'm struggling with the "/Maps/:userID" route. Let me share my r ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...

Trouble encountered with JSON integration in a PHP SQL statement

I need the server.php file to return a table of integers, each linked to a key (some integers may share a key). The table should only contain integers linked to a specific key. In order to obtain one of these keys, another key is required as a parameter. ...

Passing parameters in HTML web applications

My web application is accessible through the link ...:8080/EPQ/. It consists of a single HTML file with the following code: <input type="hidden" name="id" id ="id" > I am looking to pass a value for the 'id' parameter through the URL ...: ...

Difficulty displaying a 2D SVG in Three.js and WebGL

I am struggling to incorporate my own SVG illustration into a ThreeJS Scene that already contains a cat object and a cube. I have tried using resources like the CodePen (link included) and various Stack Overflow threads related to LegacySVG Loader, but I f ...

Navigating through hashed URLs with a Flexslider component

I have a website under construction that utilizes a flexslider, and I am looking to incorporate URL hash navigation. My goal is to extract the slide index based on the URL hash. I have examined the code for manual navigation where the index of the clicked ...

Trigger Bootstrap Modal using ASP Razor code within MVC Model value execution

I have a web application built with ASP .NET Core and MVC. The app features a side menu that allows the user to navigate through different pages based on their workflow. For example, when a user logs in for the first time, they are directed to the Home pag ...

Tips for setting elevation breakpoints for Paper components in MUI

I'm currently utilizing the MUI5 framework for my Project and I must say it's been great so far. I recently created a login page where I incorporated the Paper Component. Within the Paper Component, I wanted to specify an Elevation level. This i ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

Creating a custom jQuery plugin for exporting data

I am crossing my fingers that this question doesn't get marked as 'already answered' because I have thoroughly searched previous questions and unfortunately, my specific case is not listed anywhere. I have successfully created a jQuery func ...

What are some ways to implement src imports in Vue3?

Can you guide me on using a component in VUE3 with composition API and script setup pattern? For example, let's say I have a component named Modal. Here is how I plan to structure the folder: Modal.vue - this file will contain the Vue template and ...

Guide on managing AngularJS / JavaScript dropdowns with Python and Selenium webdriver

I am looking to automate various browser tasks using Python and the Selenium WebDriver on the Chromium browser. My Python script is currently capable of logging in, navigating to a subpage, performing clicks, and entering information into a form. However, ...

Initiating the animation/game loop for a three.js object

I am utilizing angularJS and Three.js for the frontend of my project. The Three.js object is created in the following manner: var ThreeObject = (function() { //constructor function ThreeObject() {} ThreeObject.prototype.init = functio init (){ //initial ...

Can the fluctuations in resolution of webRTC streaming video be detected?

We are currently working on a project involving WebRTC and have specific requirements that involve detecting when the resolution of the streaming video (remote stream) changes in WebRTC. Is there a way for us to achieve this? Any tips or guidance would be ...

Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' mod ...

Are variables initialized before the execution of ajax?

After reviewing the code snippet provided below, can we confirm with certainty that the id variable passed in the ajax call will consistently be assigned a value of 1? Or is there a possibility that the id could potentially be null or undefined at some p ...

The error message "Uncaught (in promise) DOMException: play() could not be executed as there was no prior user interaction with the document" indicates

var buttonColours = ["red", "blue", "green", "yellow"]; var gamePattern = []; function nextSequence() { var randomNumber = Math.floor(Math.random() * 4); var randomChosenColour = buttonColours[randomNumber]; gamePattern.push(randomChosenColour); ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

What is the proper way to execute a script and transmit arguments when the client is connected via a socket?

Is it possible to execute a script that passes arguments to a connected client using Socket.IO? Here's an example scenario: var io = require('socket.io').listen(http); io.sockets.on('connection', function (client) { console ...

Is there a way to send an array of objects to my Express / SQL Server in react?

I am currently facing a challenge with passing an array of objects to my back end (SQL Server). Below is the specific array of objects: console.info(results) Here is the array of objects named results: [0] [ [0] { [0] answer: 'bmbm,nn', [ ...