Dynamic Dropdown With Form Data Binding Laravel (v5.2+)

install
- https://github.com/laracasts/PHP-Vars-To-Js-Transformer
- https://laravelcollective.com/docs/5.2/html

** if you are using Lara v5.3 , change lists to pluck
** in this example we want to get all the towns of a specific city_id while selecting the old town_id

1- routes.php

use App\Town;

Route::group(['prefix' => 'api'], function () {
  Route::get('{city_id}/towns', function ($city_id) {
    return Town::whereCityId($city_id)->get();
  });
});

2- Controllers/PostController.php

use JavaScript;

class PostController extends Controller {

  public function edit($id)
  {
    $post = Post::findOrFail($id);

    JavaScript::put([
      'post_townId' => $post->town_id
    ]);

    return view('post.edit', compact('post'));
  }
}

3- views/post/edit.blade.php

@inject('cities','App\City')

{{ Form::model($post ,['route' => ['update.post', $post->id],'method' => 'PATCH']) }}

  {{ Form::select(
    'city_id',
    $cities->lists('name', 'id'),
    null,
    ['class'=>'form-control', 'id'=>'city'])
  }}

  <select id="town" class="form-control" name="town_id"></select>

{{ Form::close() }}

4- config/javascript.php

return [
  'bind_js_vars_to_this_view' => 'layouts.app', // or where ever u call ur js files
  'js_namespace'              => 'js_vars'      // the namespace we gonna bind our data to
];

5- js

function get_towns(id) {
  $.ajax({
    type: 'GET',
    url: '/api/' + id + '/towns',
    success: function(data) {

      $('#town').html('');

      for (i = 0; i < data.length; i++) {
        $('<option>', {
          value: data[i].id,
          text: data[i].name
        }).appendTo($('#town'));
      }

      // select the option according to old town_id
      $('#town option').filter(function() {
        return ($(this).val() == js_vars.post_townId);
      }).prop('selected', true);
    }
  });
}

$(document).ready(function() {
  get_towns($('#city').val());

  $('#city').change(function() {
    id = $(this).val();
    get_towns(id);
  });
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s