Debug School

rakesh kumar
rakesh kumar

Posted on

Currency conversion in laravel

step 1:write a html code where price and currency mention we need to convert it

  @isset($user_slug_summary)
      @if(sizeof($user_slug_summary) >0) 
      <div>
        <div class="card mt-3">
            <div class="wrap" style="margin-top: -90px;">
                <header class="cart-header cf">
                    <center><h3><strong  style="margin-left:20px;"> My Cart</strong></h3></center>                
                </header>
                <div class="cart-table">
                    <p>                  
            <li class="item" style="list-style-type: none;">
              <div class="item-main cf">                            
              <div class="row" style="margin-left:20px;">              
                <div class="col-md-8">   
     @foreach($user_slug_summary as $item)
                <div class="card" id="mycard">
                <div class="card-header" style="background-color:#706fdd">
                @if(!empty($item->slug))     
                <div class="row">
                    <div class="col-md-3">
                        <div style="color:white">Name: {{ $item->influncer_name }}</div>
                    </div>
                    <div class="col-md-4">
                        <div style="color:white">Cart Id: {{ $item->cart_id }}</div>
                    </div>
                    <div class="col-md-4">
                        <div class="total-price" data-item-id="{{ $item->id }}" style="color:white">Total Price: {{ !empty($item->record_sum) ? $item->record_sum . (!empty($item->currency) || $item->currency === [] ? $item->currency : '') : '' }}</div>
                    </div>
                    <div class="col-md-1">
                        <div>
                            <span  style="color:white" class="tp-delete" data-item-id="{{ $item->id }}"><i class="fa fa-trash"></i></span>
                        </div>
                    </div>
                </div>
            @endif
</div> 
           <div class="card-body" style="background-color:#f5eeee"  >
            <div class="item-block ib-info cf" style="width:100%">
            <div class="container">
    <div class="row">
    <div class="col-md-2">
    <div id="avatarContainer{{ $loop->iteration }}"></div>
        <script>
            var avatarHtml{{ $loop->iteration }};
            @if ($item->file_pic === null || $item->file_pic === "")
                avatarHtml{{ $loop->iteration }} = '<img style="overflow: hidden;" src="{{ url("assets/images/users/default.webp") }}" width="75" height="75">';
            @else
                avatarHtml{{ $loop->iteration }} = '<img src="/storage/images/{{ $item->file_pic }}" width="75" height="75" alt="">';
            @endif
            document.getElementById('avatarContainer{{ $loop->iteration }}').innerHTML = avatarHtml{{ $loop->iteration }};
        </script>
         </div>       
        <div class="col-md-10">  
        <div class="row">
    @foreach(json_decode($item->unpaid_cart_socials) as $platform => $price)
    <div class="col-md-4">
        @php   
        $socialUrlData = json_decode($item->currency, true);
        $currency  = $socialUrlData[$platform] ?? null;   
        @endphp                                           
        <span>
    <i class="{{ ($platform == 'koo') ? '' : 'fab fa-' . $platform }}" style="{{ ($platform == 'koo') ? 'font-size: 15px; color: black;' : '' }}">   
    @if($platform == 'koo')
            <img src="{{ url('assets/images/koo-favicon.webp') }}" width="20" style="margin-left: -9px;">
            @elseif($platform == 'scoopit')
            <img src="{{ url('assets/images/scoopit-favicon.webp') }}" width="20" style="margin-left: -9px;">
            @elseif($platform == 'slashdot')
            <img src="{{ url('assets/images/slashdot-favicon.webp') }}" width="20" style="margin-left: -9px;">
            @elseif($platform == 'roposo')
            <img src="{{ url('assets/images/roposo-favicon.webp') }}" width="20" style="margin-left: -9px;">
            @elseif($platform == 'chingari')
            <img src="{{ url('assets/images/chingari-favicon.webp') }}" width="20" style="margin-left: -9px;">             
            @elseif($platform == 'mitron')
            <img src="{{ url('assets/images/mitron-favicon.webp') }}" width="20" style="margin-left: -9px;">             
            @endif
        &nbsp;&nbsp;<b>{{ ucfirst($platform) }} :</b>
        </i>&nbsp;&nbsp;&nbsp;
        @php
        if ($price >= 10000000) {
            $shortPrice = number_format(($price / 10000000), 1) . ' Cr';
        } elseif ($price >= 100000) {
            $shortPrice = number_format(($price / 100000), 1) . ' Lakh';
        } elseif ($price >= 1000) {
            $shortPrice = number_format(($price / 1000), 1) . ' K';
        } else {
            $shortPrice = $price;
        }
    @endphp

        {{ $shortPrice }}  {{ (!empty($item->currency) || $item->currency === []) ? $item->currency : '' }}
</span><br>
    </div>
    @endforeach
</div>
        </div>
        </div>
     </div>

            </div>

        </div>
    </div>

           @endforeach
Enter fullscreen mode Exit fullscreen mode
 <div class="col-md-4">
                        <div class="total-price" data-item-id="{{ $item->id }}" style="color:white">Total Price: {{ !empty($item->record_sum) ? $item->record_sum . (!empty($item->currency) || $item->currency === [] ? $item->currency : '') : '' }}</div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

step2: create a dropdown where publisher select currency

 <div class="col-md-4 mx-auto"> 
                    <div class="card">
                        <div class="card-body">  
                            <h5>Please Select Currency</h5>                          
                        <select  class="form-control" id="currencyDropdown">
                        <option value="">Select Currency</option>
                    <option value="INR">INR</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option>
                        </select>
Enter fullscreen mode Exit fullscreen mode

Image description

step3: when we select currency we call jquery function

$('#currencyDropdown').change(function() {
    let sum=0;
    var gstRate = 18;
    let gst=0;
            var selectedCurrency = $(this).val();
            var userId = $('#auth_id').val(); // Accessing the value of the hidden input field
            console.log("my dropdown code is there"); 
            console.log(userId);
            var totalPriceArray = []; // Initialize an array to store total prices  
            let data_curr = []; // Array to store key-value pairs
            $('.total-price').each(function() {
        var total_price = $(this).text().trim(); // Get the total price text
        totalPriceArray.push(total_price); // Push the total price to the array
                 });                 
    console.log(totalPriceArray);
    const populate = async (value, currency) => {
    let myStr = ""; 

    const url = `https://api.currencyapi.com/v3/latest?apikey=cur_live_tybhSYsNrnnxzfGe7cXpU2XKdws5h1vLH1rFKHZW&base_currency=${currency}&target_currency=${selectedCurrency}`;
    const response = await fetch(url);
    const rJson = await response.json();
    console.log("Data coming");
    console.log(rJson);
    document.querySelector(".output").style.display = "block";
    const roundedValuesArray = [];

    for (let key of Object.keys(rJson["data"]))
     {
        const myvalue = rJson["data"][key]["code"];
        const roundedValue = Math.round(rJson["data"][key]["value"] * value);
        if (myvalue === selectedCurrency) {
            console.log("mera new value coming");
            console.log(roundedValue);
            roundedValuesArray.push(roundedValue);                   
                sum += roundedValue; 
        data_curr.push({ [myvalue]: roundedValue }); // Push key-value pair object into array      

                }       
           }
           console.log(sum);              
           var gst = Math.floor(sum * (gstRate / 100));           
         var sumgst= Math.floor(sum + gst);   
           $('#totalSumAllRecords').text(sum);
           $('#totalSumAllCurrency').text(selectedCurrency);
           $('#gst').text(gst);
           $('#gstsum').text(sumgst);
    console.log(roundedValuesArray);
    console.log("dekho asfdszfccsdfvdfv");
    console.log(data_curr);
    const tableBody = document.querySelector("tbody");
    tableBody.innerHTML = myStr;
};
const fetchAndPopulate = async () => {
    for (let i = 0; i < totalPriceArray.length + 1; i++) {
        const value = totalPriceArray[i].split(' ')[2];        
        const numericPart = value.match(/\d+/)[0];
        const currency = totalPriceArray[i].match(/[A-Za-z]+$/)[0];       
       await populate(numericPart, currency); // Wait for populate function to finish        
    }
};
fetchAndPopulate();
const btn = document.querySelector(".btn")
btn.addEventListener("click", (e) => {
    e.preventDefault()
    const value = parseInt(document.querySelector("input[name='quantity']").value);
    const currency = document.querySelector("select[name='currency']").value
    populate(value, currency)
})
            $.ajax({
                url: "{{ route('updateCurrency') }}",
            type: 'GET',
            data: {
                currency: selectedCurrency,
                id:userId,
                totalPriceArray: JSON.stringify(totalPriceArray), // Convert the array to JSON string                         
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {           
                console.log('Currency updated successfully');
            },
            error: function(xhr) {         
                console.error('Error updating currency');
            }
         }); 
        });
Enter fullscreen mode Exit fullscreen mode

Explnation

 var selectedCurrency = $(this).val();
            var userId = $('#auth_id').val(); // Accessing the value of the hidden input field
            console.log("my dropdown code is there"); 
            console.log(userId);
            var totalPriceArray = []; // Initialize an array to store total prices  
            let data_curr = []; // Array to store key-value pairs
            $('.total-price').each(function() {
        var total_price = $(this).text().trim(); // Get the total price text
        totalPriceArray.push(total_price); // Push the total price to the array
                 });                 
    console.log(totalPriceArray);
Enter fullscreen mode Exit fullscreen mode

output

[
    "Total Price: 70000INR",
    "Total Price: 3USD",
    "Total Price: 20000INR",
    "Total Price: 13574INR",
    "Total Price: 1234INR",
    "Total Price: 110000INR",
    "Total Price: 10000INR"
]
Enter fullscreen mode Exit fullscreen mode
console.log("dekho asfdszfccsdfvdfv");
    console.log(data_curr);
Enter fullscreen mode Exit fullscreen mode
[
    {
        "USD": 840
    },
    {
        "USD": 3
    },
    {
        "USD": 240
    },
    {
        "USD": 163
    },
    {
        "USD": 15
    },
    {
        "USD": 1320
    },
    {
        "USD": 120
    }
]
Enter fullscreen mode Exit fullscreen mode
 console.log(sum);              
           var gst = Math.floor(sum * (gstRate / 100));           
         var sumgst= Math.floor(sum + gst);   
           $('#totalSumAllRecords').text(sum);
Enter fullscreen mode Exit fullscreen mode

step 4: display data in order information after selecting currency conversion

 <div class="sub-table cf">
                        <div class="summary-block">                
                        </div>
                        <center style="margin-bottom:10px;"><b>Order Information</b></center>
                        <h7>Amounting ({{$totalItems}} item) :<span id="totalSumAllRecords" style="float: right;">{{$totalSumAllRecords}}</span><span id="totalSumAllCurrency" style="float: right;"></span></h7><br>                       
                        <h7>Gst :<span id="gst" style="float: right;">{{$gst}}</span></h7><br>
                        <h7>Total (including Gst)  :<span id="gstsum" style="float: right;">{{$total}}</span></h7>

                         </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)