zaster's avatar

Dependent Dropdown - Jquery - Ajax

A customer can be assigned to many companies. Therefore when the customer is selected the respective companies should appear. Instead of the company names, i am getting the company_ids How can i get the company names

JobController.php

public function edit(Job $job)
    {
        $subJobs = $job->sub_jobs;
        $customers = User::all();
        $selectedCustomer = $job->user_id;
        //dd($selectedCustomer);
        $companies = Company::all();
        $selectedCompany = $job->company_id;
        return view('employees.jobs.edit', compact('job', 'subJobs', 'customers', 'selectedCustomer', 'companies', 'selectedCompany'));
    }


    public function ajax(Job $job)
    {
      //Get the Job Number
      $id = $job->id;

      //Get the user_id of the job
      $userId = Job::where('id', '=', $id)->pluck('user_id')->first();

      //Show all customers
      $customers = User::all();
      //dd($customers);
      //Show the companies according to the customer list
      $companies = Job::where('user_id', '=', $userId)
                        ->pluck('company_id')->unique();
      //dd($companies);
      return json_encode($companies);

    }

public function update(Request $request, Job $job)
    {
        $this->validate($request, [
          'job_owner' => 'required'
        ]);

        //dd($request);
        $customer = new User();
        $customer->user_id = $request['customer'];


        $customer = User::Find($request['customer']);
        $customer->companies()->attach($request['company']);
        $customer->save();

        $job->user_id = $request['customer'];
        $job->company_id = $request['company'];
        $job->description= $request['description'];
        $job->owner= $request['owner'];
        $job->status= $request['status'];
        $job->despatch_status= $request['despatch_status'];
        $job->invoice_status= $request['invoice_status'];
        $job->sales_status= $request['sales_status'];
        $job->entered_status= $request['entered_status'];
        $job->delivery_date= $request['delivery_date'];
        $job->delivery_time= $request['delivery_time'];
        $job->comp= $request['comp'];
        $job->cost= $request['cost'];
        $job->profit= $request['profit'];
        $job->price= $request['price'];
        $job->nbt= $request['nbt'];
        $job->vat= $request['vat'];
        $job->total_value= $request['total_value'];
        $job->save();

        $jobs = Job::all();
        return view('employees.jobs.job', compact('jobs', $jobs));
    }
    

jobs.edit.blade.php

<form action="{{ route('employee.job.update',$job->id) }}" method="post">
      @method('PUT')
      @csrf
      <div class="form-group">
        <label for="inputJobNumber">Job Number</label>
        <input type="text" class="form-control" id="inputJobNumber" name="id" value="{{$job->id}}" readonly>
      </div>
      <div class="form-group">
        <label for="inputCustomerName">Customer Name</label>
          <select name="customer" class="form-control" id="inputUser">
             <option value="">--Select User--</option>
             @if ($customers->count())
               @foreach ($customers as $customer)
               <option value="{{ $customer->id }}" {{ $selectedCustomer == $customer->id ? 'selected="selected"' : '' }}>
                  {{ $customer->name }}
                </option>
               @endforeach
             @endif
          </select>
      </div>
      <div class="form-group">
        <label for="inputCustomerName">Company Name</label>
          <select name="company" class="form-control" id="inputCompany">
             <option value="">--Select Company--</option>
             @if ($companies->count())
             @foreach ($companies as $key => $value)
             <option value="{{ $key }}" {{ $selectedCompany == $key ? 'selected="selected"' : '' }}>
               {{ $value->name }}
             </option>
             @endforeach
           @endif 

Jquery of jobs.edit.blade.php

<script type="text/javascript">
      $(document).ready(function() {
          $('select[name="customer"]').on('change', function() {
              var cusotmerId = $(this).val();
              if(cusotmerId) {
                  $.ajax({
                      url: '/employee/job/ajax/'+cusotmerId,
                      type: "GET",
                      dataType: "json",
                      success:function(data) {
                          $('select[name="company"]').empty();
                          $.each(data, function(key, value) {
                              $('select[name="company"]').append('<option value="'+ key +'">'+ value +'</option>');
                          });
                      }
                  });
              }else{
                  $('select[name="company"]').empty();
              }
          });
      });
  </script>
0 likes
4 replies
Sergiu17's avatar

Looks like you pluck only the company_id

$companies = Job::where('user_id', '=', $userId)
                        ->pluck('company_id')->unique();

but you need to pluck the name too

$companies = Job::where('user_id', '=', $userId)
                        ->pluck('company_id', 'name')->unique();
zaster's avatar

@Sergiu17 struggling with the ajax part now. Company names are not getting changed according to the user name

zaster's avatar

@Sergiu17 Actually the company name should be taken from the companies table not the jobs table. That seems like the main issue here now.

zaster's avatar

I need to do something like this

$companies = DB::table('jobs')
                  ->where('user_id', '=', $userId)
                  ->join('companies', 'jobs.company_id', '=', 'companies.id')
                  ->get()
                  ->unique();

I need to get the company_ids when the user_id is given

Please or to participate in this conversation.