Laravel Select onChange – Ajax Request via Laravel Controller

Send Ajax GET Request on-change of select-box and handle it via Laravel Controller Part-1

Mostly Laravel users are searching for the problem regarding select box via Ajax request and handling it through Laravel Controller not by Anonymous Route function, so this article might help those who are still looking for answers OR couldn’t find anything good on the internet.

So let me just clear you what I’m going to do in this Tutorial, I’ve a table name “Company” and a table name “Packages” in my Database. They are in a One-to-Many Relationship with one-another, as A “Company” can have many “Packages” and a “Package” belongs-to a “Company”.

So when a User selects a Company from the select-box, another select box will appear with all the Packages of the respective Company. [see image below for illustration]

select-box-onchange-ajax-laravel-controller-3

Here how its done.

My “Select A Company” select box:

<div class="col-xs-3">
 <label>Select a Company</label>
 <select id="company" name="company" class="form-control">
 <option>---</option>
 <option value="4"> 4. Company #4 </option>
 <option value="6"> 6. Company #6 </option>
 <option value="27"> 27. Company #27 </option>
 <option value="26"> 26. Company #26 </option>
 <option value="1"> 1. Company #1 </option>
 </select>
 </div>

select-box-onchange-ajax-laravel-controller

Note that I’ve given the “id” attribute of “select box” as “company” which I’ll use it in my Ajax request.

And here is my Ajax:

<script>
 $('#company').change(function(e)
 {
 e.preventDefault();

$y = $(this).val();
  alert($y);

$.ajax
 ({
 url: '{{ url('getpackages') }}/'+$y,
 type: 'GET',
 dataType: 'json',
 success: function(data)
 {
 console.log(data);
 }
 });
 });
 </script>

In the first line, I’m telling jQuery to trigger the change event on “#company” select-box (using “#” with company as I’ve given “id” attribute of select box as “company”) and preventing the default behavior. I stored the value attribute of the selected company into a variable named “$y” and alert it just to make sure I’m getting the respective value.

Then, in my ajax, I’m using Laravel’s Helper Function “url” and specify which route to hit i.e. “getpackages” along with the selected company value which we’ve stored in variable “$y”.
Here’s my Route:

Route::get('getpackages/{val}', 'GroupController@getpackages');

here “{val}” will receive the value of “$y” and pass it to the “getpackages method” of “GroupController”.

Here’s my Controller:

public function getpackages($id)
 {

return $id;

}

As “getpackages method” accepts a parameter, so “$id” will be the value of the selected company which we have passed it via Ajax.

Just for testing, return this “$id” and check your browser’s console; you will surely be getting the value of the selected company. [see image below]

select-box-onchange-ajax-laravel-controller-4

So we are getting somewhere near to our end result as we are getting the “id” or “value” of the selected company.

Now, as I’ve mentioned above, Company and Packages are in a One-to-Many Relationship, so here’s my “getpackages method”:

public function getpackages($id)
 {

$company = Company::findOrFail($id);
 $packages = $company->packages;

}

Here, “findOrFail” is other Helper function of Laravel, which will try to find the “id” within Company’s Table and returns the matched object if found.. else fails!

So, we stored it into a variable “$company” and then look for its Packages and stored that collection into another variable “$packages”.

If you don’t know how Relationship works in Laravel, do follow Laravel’s Documentation for now and I’ll make sure to write another article for Laravel’s Eloquent ORM.

So till now, we have a Company in “$company” and its Packages in “$packages” but we have to append another select box with all the Packages a Company have like pictured in the image above; there are two ways to do this:

Way #1: dataType – HTML

Scroll up a bit and go to the Script section where we write the ajax request, there we write dataType: ‘json’, but for HTML, change it to dataType: ‘html’.

This dataType is actually the type of data that you’re expecting back from the server. It can be xml, json, script, or html.

As we’ve declared the dataType to html, extend your “getpackages method” as:

public function getpackages($id)
 {

$company = Company::findOrFail($id);
 $packages = $company->packages;

// Send as HTML

$html = '';

$html .= '<select id="remove_select" name="packages" class="form-control">';
 $html .= '<option> --- </option>';
 foreach ($packages as $package)
 {
 $html .= '<option value="'.$package->id.'"> '.$package->id.'. '.$package->package_name.' </option>';
 }
 $html .= '</select>';

return $html;
 }

Here we are just storing html in a variable and return that variable to the ajax call.

Note that I’ve given an “id = remove_select” to select-box so that when ever a change occurs we will remove the old options in it and new options will populate.

See below script for better understanding:

Update your script to:

<script>
 $('#company').change(function(e)
 {
 e.preventDefault();

$y = $(this).val();
 //alert($y);

$("select").remove( "#remove_select" );

$.ajax
 ({
 url: '{{ url('getpackages') }}/'+$y,
 type: 'GET',
 dataType: 'html',
 success: function(data)
 {
 $("#package_div_html").append(data);
 }
 });
 });
 </script>

In the images above, you can see I’ve “Select a Package” div which I’ve given “id” as “package_div_html”. So on success of ajax call, we will append all the html to that div.

select-box-onchange-ajax-laravel-controller-3

So guys this was Way #1 using dataType as html. For Way #2, see my next article in which I’ll use dataType as json.

2 thoughts on “Laravel Select onChange – Ajax Request via Laravel Controller

Leave a Reply

Your email address will not be published. Required fields are marked *