Making Dynamic Address Field on Laravel Form, for Address Collection – Laravel 8.x

Hello world! Welcome to “TechBlog” and Today we are going to make dynamic address collection form through drop down input.

Well, in this context I have some observations as a developer for you. why we do so with an address field. We can take input as a whole or separately, by a text input box easily rather why we are creating such a complex mechanism.

We do so, because of analytics, for example if we take input through text box there might differently spelling of same district, or might user have mistaken in any point of time. In that case, it is difficult to find out the sales or demographics analytics for big organization or company. Hence this concept dynamic load of demographic data is useful with 100% accuracy

View on Youtube:

Database Structure:

-- --------------------------------------------------------

--
-- Table structure for table `geo_locations`
--

CREATE TABLE `geo_locations` (
  `id` int NOT NULL,
  `name` varchar(100) NOT NULL,
  `parent_id` int DEFAULT NULL,
  `external_id` varchar(10) DEFAULT NULL,
  `location_type` varchar(20) NOT NULL,
  `pin` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

----------------------------------------------------------

Download Database SQL file Here:

Web Routes:

Route::get('/', ['as'=>'home', 'uses'=> '[email protected]']);

Route::post('/district-name', ['as'=>'district', 'uses'=>'[email protected]']);

Route::post('/ps-name', ['as'=>'ps', 'uses'=>'[email protected]']);

Controller:

By default Laravel has a default controller, but we are going to create a new controller for me. So, in order to do that, type php artisan make:controller Geolocation.

Open up the controller in code editor, we have to create function home inside Geolocation controller and return your view over here.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Respoce;
use Illuminate\Support\Arr;
use App\Models\GeoLocations;


class Geolocation extends Controller
{
    //
    protected $view_path = 'student';

    public function home(){

        //return view of your form.

        $data=[];
        $data['state']= GeoLocations::where('location_type', 'STATE')->pluck('name','id')->toArray();
        return view($this->view_path.'.register', compact('data'));
    }

    public function getDist(Request $request){
        $data=GeoLocations::where('location_type','DISTRICT')->where('parent_id',$request->id)->select('name', 'id')->get();
        return json_encode($data);
    }

    public function getPS(Request $request){
        $data=GeoLocations::where('location_type','SUBDISTRICT')->where('parent_id',$request->id)->select('name', 'id')->get();
        return json_encode($data);
    }    

}

Models:

Now from database we need to fetch data for dropdown. For that we need a model that construct table collections. So, in order to do that go to terminal and type php artisan make:model GeoLocations

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class GeoLocations extends Model
{
    use HasFactory;
    public $table= "geo_locations";
    protected $fillable =['id', 'name','parent_id', 'external_id', 'location_type', 'pin'];
}

Views:

<link rel="stylesheet" href="{{ asset('assets/css/select2.min.css') }}" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
    .form-group {
        margin-top: 15px;
        padding-top: 45px;
    }
</style>
<div class="main-content">
    <div class="main-content-inner">
        <div class="page-content">
            <div class="row">
                <div class="col-xs-12 ">{!! Form::open(array('url' => '/')) !!} <span class="label label-info arrowed-in arrowed-right arrowed responsive">Red mark input are required. </span>
                    <hr class="hr-16">
                    <div class="form-group">{!! Form::label('address', 'Address', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-8">{!! Form::text('address', null, ["class" => "form-control border-form upper","required"]) !!}</div>{!! Form::label('state', 'State', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-2">{!! Form::select('state', $data['state'],null, ["class" => "form-control border-form upper","required", "onChange" => "loadDistrict(this);"]) !!}</div>
                    </div>
                    <div class="form-group">{!! Form::label('district', 'District', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-2">
                            <select id="district" name="district" class="form-control district" onChange="loadPs(this)" ;>
                                <option>Select Dist</option>@if(isset($data['district'])) @foreach($data['district'] as $key)
                                <option selected value="{{$key->id}}">{{$key->name}}</option>@endforeach @endif</select>
                        </div>{!! Form::label('ps', 'P.S./Sub.Div', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-2">
                            <select id="ps" name="ps" class="form-control ps">
                                <option>Select PS</option>@if(isset($data['ps'])) @foreach($data['ps'] as $key)
                                <option selected value="{{$key->id}}">{{$key->name}}</option>@endforeach @endif</select>
                        </div>{!! Form::label('pincode', 'Pincode', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-2">{!! Form::text('pincode', null, ["class" => "form-control border-form upper","required"]) !!}</div>{!! Form::label('country', 'Country', ['class' => 'col-sm-1 control-label']) !!}
                        <div class="col-sm-2">{!! Form::text('country', 'INDIA', ["class" => "form-control border-form upper","required"]) !!}</div>
                    </div>
                </div>
            </div>
        </div>{!! Form::close() !!}</div>
    <!-- /.col -->
</div>

Java Scripts:

<script type="text/javascript">
    function loadDistrict($this){
        $.ajax({
            type: 'POST',
            url: '{{ route('district') }}',
            data: {
                _token: '{{ csrf_token() }}',
                id: $this.value
            },
            success: function (response) {
                var data = $.parseJSON(response);
                if (data.error) {
                    $.notify(data.message, "warning");
                } else {
                	$('.district').html('').append('<option value="0">Select Dist</option>');
                    $.each(data, function(key,valueObj){
                        $('.district').append('<option value="'+valueObj.id+'">'+valueObj.name+'</option>');
                    });
                }
            }
        });
    }

    function loadPs($this){
        $.ajax({
            type: 'POST',
            url: '{{ route('ps') }}',
            data: {
                _token: '{{ csrf_token() }}',
                id: $this.value
            },
            success: function (response) {
                var data = $.parseJSON(response);
                if (data.error) {
                    $.notify(data.message, "warning");
                } else {
                    $('.ps').html('').append('<option value="0">Select ps</option>');
                    $.each(data, function(key,valueObj){
                        $('.ps').append('<option value="'+valueObj.id+'">'+valueObj.name+'</option>');
                    });
                }
            }
        });
    }
</script>

Conclution:

Finally, we made a form that collect address from user dynamicaly in laravel.

The following two tabs change content below.

Subroto Mondal

Chief Coordinator HR&CR
I like Programming and New Technologies. And work with Linux.

Latest posts by Subroto Mondal (see all)

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.