You can't use blade templating in JS files.

Now you have 2 things you can do:

  1. Move your snippet of javascript from js file to the bottom of the "view.blade.php"
  2. You can declare in the "view.blade.php" the variables that contain options, and then get it from javascript.

For example:

Your "view.blade.php" would be:

<table width="100%">
    <tbody class="input_fields_Pesanan">
        <tr>
            <td style="width: 15%;" align="center"><b>Kode BMN</b></td>
            <td style="width: 15%;" align="center"><b>Nama Barang</b></td>
            <td style="width: 15%;" align="center"><b>Kuantitas</b></td>
            <td style="width: 15%;" align="center"><b>Satuan Ukuran</b></td>
            <td style="width: 2%;"></td>
        <tr>
            <td>
                <select type="text" style="width: 100%;" class="form-control select2" id="kode_bmn" name="kode_bmn" data-placeholder="--Pilih Kode BMN--">
                    <option></option>
                    @foreach(b)
                    <option>{{$b->kode_bmn}}-{{$b->nama_bmn}}</option>
                    @endforeach
                </select>
            </td>    
            <td><input type="text" class="form-control " id="jenis_barang" name="jenis_barang" ></td>
            <td><input type="number" min="1" class="form-control" id="kuantitas" name="kuantitas"></td>
            <td>
                <select type="text" style="width: 100%;" class="form-control select2" id="satuan_ukuran" name="satuan_ukuran" data-placeholder="--Pilih Satuan Ukuran--">
                    <option></option>
                    <option>m</option>
                    <option>unit</option>
                    <option>kg</option>
                </select>
            </td>
            <td>&nbsp;<button class="add_field_pesanan" title="Tambah Field Pesanan"><i class="fas fa-plus"></i></button></td>
        </tr>
    </tbody> 
</table>
<script>
    var myOptions = '@foreach(b) <option>{{$b->kode_bmn}}-{{$b->nama_bmn}}</option> @endforeach';
</script>

And then your Javascript file would be:

$(document).ready(function() {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper_pesanan = $(".input_fields_Pesanan"); //Fields wrapper
    var add_pesanan = $(".add_field_pesanan"); //Add button ID

    var x = 1; //initlal text box count
    $(add_pesanan).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper_pesanan).append('<tr><td><select type="text" style="width: 100%;" class="form-control select-new-' + x + '" id="kode_bmn" name="kode_bmn" data-placeholder="--Pilih Kode BMN--"><option></option>' + myOptions + '</select></td><td><input type="text" class="form-control " id="jenis_barang" name="jenis_barang" ></td><td><input type="number" min="1" class="form-control" id="kuantitas" name="kuantitas"></td><td><select type="text" style="width: 100%;" class="form-control select-new-' + x + '" id="satuan_ukuran" name="satuan_ukuran" data-placeholder="--Pilih Satuan Ukuran--"><option></option><option>m</option><option>unit</option><option>kg</option></select></td><td>&nbsp;&nbsp;&nbsp;<a href="#" class="remove_pesanan" title="Hapus"><i class="fas fa-trash-alt"></i></a></td></tr>'); // add input boxes.

            //instantiate the new select as select2
            $('select.select-new-' + x).select2();
        }
    });

    $(wrapper_pesanan).on("click",".remove_pesanan", function(e){
        e.preventDefault(); $(this).parent('td').parent('tr').remove(); x--;
    });
});

Obviously make sure the snippet in view.blade.php comes before of including your javascript, otherwise you get a undefined from javascript.

Answer from Bacca001 on Stack Overflow
Top answer
1 of 1
2

You can't use blade templating in JS files.

Now you have 2 things you can do:

  1. Move your snippet of javascript from js file to the bottom of the "view.blade.php"
  2. You can declare in the "view.blade.php" the variables that contain options, and then get it from javascript.

For example:

Your "view.blade.php" would be:

<table width="100%">
    <tbody class="input_fields_Pesanan">
        <tr>
            <td style="width: 15%;" align="center"><b>Kode BMN</b></td>
            <td style="width: 15%;" align="center"><b>Nama Barang</b></td>
            <td style="width: 15%;" align="center"><b>Kuantitas</b></td>
            <td style="width: 15%;" align="center"><b>Satuan Ukuran</b></td>
            <td style="width: 2%;"></td>
        <tr>
            <td>
                <select type="text" style="width: 100%;" class="form-control select2" id="kode_bmn" name="kode_bmn" data-placeholder="--Pilih Kode BMN--">
                    <option></option>
                    @foreach(b)
                    <option>{{$b->kode_bmn}}-{{$b->nama_bmn}}</option>
                    @endforeach
                </select>
            </td>    
            <td><input type="text" class="form-control " id="jenis_barang" name="jenis_barang" ></td>
            <td><input type="number" min="1" class="form-control" id="kuantitas" name="kuantitas"></td>
            <td>
                <select type="text" style="width: 100%;" class="form-control select2" id="satuan_ukuran" name="satuan_ukuran" data-placeholder="--Pilih Satuan Ukuran--">
                    <option></option>
                    <option>m</option>
                    <option>unit</option>
                    <option>kg</option>
                </select>
            </td>
            <td>&nbsp;<button class="add_field_pesanan" title="Tambah Field Pesanan"><i class="fas fa-plus"></i></button></td>
        </tr>
    </tbody> 
</table>
<script>
    var myOptions = '@foreach(b) <option>{{$b->kode_bmn}}-{{$b->nama_bmn}}</option> @endforeach';
</script>

And then your Javascript file would be:

$(document).ready(function() {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper_pesanan = $(".input_fields_Pesanan"); //Fields wrapper
    var add_pesanan = $(".add_field_pesanan"); //Add button ID

    var x = 1; //initlal text box count
    $(add_pesanan).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper_pesanan).append('<tr><td><select type="text" style="width: 100%;" class="form-control select-new-' + x + '" id="kode_bmn" name="kode_bmn" data-placeholder="--Pilih Kode BMN--"><option></option>' + myOptions + '</select></td><td><input type="text" class="form-control " id="jenis_barang" name="jenis_barang" ></td><td><input type="number" min="1" class="form-control" id="kuantitas" name="kuantitas"></td><td><select type="text" style="width: 100%;" class="form-control select-new-' + x + '" id="satuan_ukuran" name="satuan_ukuran" data-placeholder="--Pilih Satuan Ukuran--"><option></option><option>m</option><option>unit</option><option>kg</option></select></td><td>&nbsp;&nbsp;&nbsp;<a href="#" class="remove_pesanan" title="Hapus"><i class="fas fa-trash-alt"></i></a></td></tr>'); // add input boxes.

            //instantiate the new select as select2
            $('select.select-new-' + x).select2();
        }
    });

    $(wrapper_pesanan).on("click",".remove_pesanan", function(e){
        e.preventDefault(); $(this).parent('td').parent('tr').remove(); x--;
    });
});

Obviously make sure the snippet in view.blade.php comes before of including your javascript, otherwise you get a undefined from javascript.

🌐
Laracasts
laracasts.com › discuss › channels › javascript › push-laravel-collection-in-a-javascript-aray
Push Laravel collection in a javascript aray
$(document).ready(function() { var data = []; @foreach($products as $product ) data.push({'{{ $product->id }}' : '{{ $product->name }}'}); @endforeach // Im trying to get a variable which looks like this // data: [ // { // id: 'The ID goes here', ...
Discussions

php - Use foreach loop in javascript in laravel - Stack Overflow
I have data am looping from controller and i have a graph script and i want to loop that data in the script so that it can draw the graph based on that data In controller i have $records = Products:: More on stackoverflow.com
🌐 stackoverflow.com
php - How to create javascript function in laravel foreach loop - Stack Overflow
I need some help about this code I have some code in blade view @foreach($cart as $ct) More on stackoverflow.com
🌐 stackoverflow.com
November 3, 2019
javascript - How to do foreach in JS using data from laravel views? - Stack Overflow
If the L is convertible to Array or it's already an array it should work. For more information about forEach loops check here! More on stackoverflow.com
🌐 stackoverflow.com
php - Using javascript function on foreach loop in laravel blade - Stack Overflow
I want to use javascript for word limit on tags, using foreach loop. It works pretty well but only works on the first data, like this: This is how my foreach seems like: More on stackoverflow.com
🌐 stackoverflow.com
April 24, 2020
Top answer
1 of 1
1

Following is approach using addEventListener() and classes to target elements as well as data attributes (like data-target="myForm1") for element specific data to use inside an event handler.

It is currently working for the "Edit" and "Cancel" buttons which have the same class popup-toggle along with their other existing classes.

You can use this approach as a template for your other elements/actions

// in DOMContentLoaded event handler or after elements exist

const popToggleButtons = document.querySelectorAll('.popup-toggle');

[].slice.call(popToggleButtons).forEach(function(btn) {
  btn.addEventListener('click', handleToggleBtnClick)
});


function handleToggleBtnClick(event) {
  const btnData = this.dataset,
    popup = document.getElementById(btnData.target),
    classMethod = btnData.action === 'show' ? 'add' : 'remove';
  // add or remove active class depending on which button was clicked
  popup.classListclassMethod;

}
.form-popup {
  display: none
}

.form-popup.active {
  display: block
}
<div>
  <button type="button" data-target="myForm1" data-action="show" class="popup-toggle btn-btn-delete">
        <i class="mr-1 fas fa-edit"></i>Edit #1
</button>
  <div class="form-popup" id="myForm1">
    <form action="..." class="form-container" method="post">
      <h1>Edit information #1</h1>
      <input type="text" name="name" value="name 1">
      <button type="submit" class="btn">change</button>
      <button type="button" class="btn cancel popup-toggle" data-target="myForm1" data-action="hide">Close</button>
    </form>
  </div>
</div>
<div>
  <button type="button" data-target="myForm2" data-action="show" class="popup-toggle">
        <i class="mr-1 fas fa-edit"></i>Edit #2
</button>

  <div class="form-popup" id="myForm2">
    <form action="..." class="form-container" method="post">
      <h1>Edit information #2</h1>
      <input type="text" name="name" value="name 2">
      <button type="submit" class="btn">change</button>
      <button type="button" class="btn cancel popup-toggle" data-target="myForm2" data-action="hide">Close</button>
    </form>
  </div>
</div>

Top answer
1 of 1
1

You need to select all of your paragraphs and apply your truncate to each.

I have commented in the code below:

function truncateText(el, maxLength) {
  // no need to querySelector here now, 
  // as we have passed in the element
  let truncated = el.innerText;

  if (truncated.length > maxLength) {
      truncated = truncated.substr(0, maxLength) + '...';
  }
  return truncated;
}

// Run your truncate function when tyhe DOM has loaded
document.addEventListener('DOMContentLoaded', (event) => {
  // select all your P's using querySelectorAll
  const ps = document.querySelectorAll('p');
    
  // for each p, run your turncate function, passing the *element*
  ps.forEach((p) => {p.innerText = truncateText(p, 50);});
});
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget imperdiet odio, hendrerit egestas neque. Pellentesque lobortis pulvinar rutrum. Donec eros eros, fermentum vitae tempus ut, suscipit in ligula. Maecenas et scelerisque erat, suscipit lobortis metus. In aliquet velit ac velit mollis luctus. Sed dapibus arcu eget enim vestibulum elementum. Nunc vel ultrices erat.</p>

🌐
Laravel
laravel.com › docs › 5.3 › blade
Blade Templates | Laravel 5.3 - The clean stack for Artisans and agents
This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop: ... @foreach ($users as $user) @if ($loop->first) This is the first iteration.
Find elsewhere
Top answer
1 of 2
2

In this case, as the HTML you want to append is governed by the content coming from your Laravel back end, it would make far more sense to de-couple the HTML and the JS. As such, create the HTML in the DOM when the page loads and hide it. Then in the JS you can clone that HTML and append it where it is required to be displayed. Something like this:

$('.add-new-product').on('click', function() {
  var $clone = $('#new-product-content > div').clone();
  $clone.appendTo('#products-div');
});
#new-product-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="add-new-product">Add New<i class="fa fa-plus"></i></span>
<div id="products-div"></div>

<div id="new-product-content">
  <div class="col-xs-12">
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon input-group-addon-small"><i class="sicon-tag-special"></i></span>
        <select class="form-control" name="category_id" style="width: 100%">
          <option value="">Select Category...</option>
          <!-- 
          output your categories here, eg.
          @foreach($categories as $category)
            <option value="{{ $$category->id }}">{{ $category->name }}</option>
          @endforeach
        
          Below is just for demo purposes... -->
          <option value="lorem">Lorem</option>
          <option value="ipsum">Ipsum</option>
          <option value="dolor">Dolor</option>
          <option value="sit">Sit</option>
        </select>
      </div>
    </div>
  </div>
</div>

Also note the use of unobtrusive event handlers here. Using inline event handlers in your HTML, such as onclick etc., is bad practice and should be avoided where possible.

2 of 2
1

You could do something like this:

function createProduct() {
  // Echo the JSON for the options in your JS
  var options =  @json($categories);
  // Map options to their HTML version, and join them
  var optionsHtml = options.map(function (opt) {
    return '<option value="' + opt.id + '">' + opt.name + '</option>';
  }).join('');

  var html = '   <div class="col-xs-12">'
           + '      <div class="form-group">'
           + '          <div class="input-group">'
           + '               <span class="input-group-addon input-group-addon-small"><i class="sicon-tag-special"></i></span>'
           + '               <select class="form-control" name="category_id" style="width: 100%">'
           + '                  <option value="">Select Category.. </option>'
           +                    optionsHtml // Add them here
           + '               </select>'
           + '          </div>'
           + '       </div>'
           + '    </div>';

     $('#products_div').prepend(html);
 }
🌐
Laravel
laravel.com › docs › 8.x › blade
Blade Templates | Laravel 8.x - The clean stack for Artisans and agents
April 28, 2020 - If the child view requires these variables, you should use the @foreach and @include directives instead. The @once directive allows you to define a portion of the template that will only be evaluated once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page's header using stacks.
🌐
ItSolutionstuff
itsolutionstuff.com › post › laravel-blade-foreach-loop-exampleexample.html
Laravel Blade Foreach Loop Example - ItSolutionstuff.com
April 16, 2024 - simple example of foreach loop statement in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11. ... I hope it can help you... ... I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers ...
🌐
Laracasts
laracasts.com › discuss › channels › laravel › show-ajax-response-with-foreach-loop-in-blade
show ajax response with foreach loop in blade
I have an ajax request which returns array (Json). how can I use this array in blade in a "foreach" ? <script type="text/javascript"> $('#filters').on('change' , function (e) { var filter_name = e.target.value; $.get("{!! route('shop') !!}", { 'filter_name' : filter_name }, function (data) { //
🌐
Laracasts
laracasts.com › index.php › discuss › channels › laravel › foreach-variable-id-for-each-item
Foreach, variable "id" for each item ?
@foreach ($items as $item) <p><span more_id="{{ $loop->index }}" class="more">...</span><span id="more-{{ $loop->index }}">{{$item['Description']}}</span></p> @endforeach · Then you apply your javascript code on all span with the more class.
🌐
Laracasts
laracasts.com › discuss › channels › laravel › how-to-loop-through-this-array
How to loop through this array?
$categoryid = $request->category_id; $locationid = $request->location_id; $category = Category::where('id', $categoryid)->first(); $cities = Location::where('id', $locationid)->pluck('city'); $cityname = $cities[0]; $alllocations = []; $ratecards = []; $locations = []; $father = []; $i = 0; $filteredlocations = $category->locations->where('city', $cityname)->all(); foreach($filteredlocations as $location){ $alllocations[$i] = $location->getaddetails; $ratecards[$i] = $location->ratecard; $i++; } $father[0] = $alllocations; $father[1] = $ratecards; return view('ads', compact('father')); }
🌐
Medium
devtalk94.medium.com › laravel-each-vs-foreach-performance-comparison-which-is-faster-e1f3189ec902
Laravel each() vs foreach() Performance Comparison: Which is Faster? | by Dev Talk | Medium
September 2, 2025 - foreach ($array as $key => $value) { // Your logic here } ... Software Engineer with extensive experience in full-stack web development, specializing in Laravel, JavaScript, and scalable backend systems.
🌐
Stack Overflow
stackoverflow.com › questions › 65049972 › how-to-access-all-foreach-loop-data-in-js-from-laravel-blade
javascript - How to access all foreach loop data in JS from laravel blade? - Stack Overflow
I am displaying data in foreach loop in laravel blade where I only display ten records per page and I have used pagination for showing all records. Now I want to develop a search or filter function...
🌐
Laracasts
laracasts.com › discuss › channels › laravel › foreach-over-writing-records-with-javascript-iteration-of-row
foreach over writing records with javascript iteration of row
public function update(Request $request, $id) { $invoice = Invoice::find($id); $invoice->client_id = $request->client_id; $invoice->date = $request->date; $invoice->due_date = $request->due_date; $invoice->title = $request->title; $invoice->recurring = $request->recurring; $invoice->subtotal = $request->subtotal; $invoice->discount = $request->discount; $invoice->discounted = $request->discounted; $invoice->total = $request->total_amount; $invoice->terms = $request->terms; $invoice->save(); if ($invoice->save()) { foreach ($request->items as $item) { DB::table('invoice_item')->update([ 'invoic
🌐
TechvBlogs
techvblogs.com › blog › laravel-blade-foreach-loop-example
Laravel Blade Foreach Loop Example
April 23, 2025 - You can see this in the below example. <!DOCTYPE html> <html> <head> <title>Laravel Blade Foreach Loop Example - TechvBlogs</title> </head> <body> <ul> @foreach ($users as $user) <li>Id: {{ $user['id'] }}, Name: {{ $user['name'] }}</li> @if ($loop->last) <li>Last Data</li> @endif @endforeach </ul> </body> </html>
🌐
Laracasts
laracasts.com › discuss › channels › code-review › accessing-json-object-with-foreach
Accessing JSON object with foreach
im super confused how i can access this json object that im sending to my view in laravel. I was reading a few places that i need to decode this json ($json = json_decode($json)) first but that gives me htmlspecial chars error. With json as this: [{ "ClientID":24, "Name":"Client1", "Balance1":null, "Balance2":null }, { "ClientID":25, "Name":"Client2", "Balance1":24, "Balance2":0 }] I tried a few variations of this @foreach statement but im lost how to enter this object!!