mafortis
mafortis

Reputation: 7128

Getting data relations by javascript in laravel

Sorry for title I really didn't know how to describe it.

I have data returned by JavaScript but my data has other data ORM related which i need those as well.

this is my data that returned on selected option:

Object { id: 1, address: "hrktgui erhoutruei9utgy", postalcode: "154785", user_id: 1, city_id: 1, state_id: 10, country_id: 102, created_at: "2018-02-09 13:28:22", updated_at: "2018-02-09 13:28:22" }

I need this data:

  1. address
  2. postalcode
  3. city name (provided under city_id)
  4. state name (provided under state_id)

My issue is to retrieving that city and state name

later i want add this 4 data as hidden input to my view so I can use it for my other function.

here is my js code:

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="address_id"]').on('change', function() {
      var addressID = $(this).val();
      if(addressID) {
      $.ajax({
        url: '{{ url('addressdetails') }}/'+encodeURI(addressID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('div#details').empty();
        console.log(data['address']);
        console.log(data);
        // $.each(data, function(key, value) {
        //     $('div#details').append('<input type="hidden" name="shipment_price" value="'+...+'"><input type="hidden" name="shipment_price" value="'+...+'">');
        //     });
        }
      });
      }else{
        $('div#details').empty();
      }
    });
  });
</script>

my html:

<div id="details"></div>

my function:

public function getAddressDetails($id)
{
        $address = Address::findOrFail($id);
        return response()->json($address);
}

my route:

Route::get('addressdetails/{id}', 'CartController@getAddressDetails');

Upvotes: 0

Views: 556

Answers (1)

ZeroOne
ZeroOne

Reputation: 9117

its an object. try this.

success:function(data) {
        var statename = data.state.name;
        var cityname = data.city.name;
}

Edit: "my issue is to retrieving that city and state names"

your query need to use eager loading

example:

return response()->json(Address::with(['city','state'])->find($id));

in Address Model

class Address {
      ...
      ...
      public function city(){
          return $this->belongsTo(City::class);
      }
      public function state(){
          return $this->belongsTo(State::class);
      }
}

Upvotes: 3

Related Questions