0

in javascript i am trying to achive some result in laravel blade using

<script>
 var $a = 10;
 var productIn = @json($product->where('category_id' , $a)->pluck('id')->toArray());
   console.log(productIn);
</script>

if i use 'category_id' , 10 it works fine but if i use $a blade view gives error undefined variable $a i have searched a lot but i think no body asked this question any idea will be preferable thanks

Hamza Qureshi
  • 172
  • 2
  • 20
  • 2
    `$a` is a JS variable, and can't be used in `->where()`, which is a PHP function. You shouldn't be doing _any_ of this in a view, let alone a JS script. Define `$productIn` somewhere in a Controller, then pass it to a view. – Tim Lewis Jan 17 '23 at 19:01
  • but where works fine if i use where('category_id' , 10) – Hamza Qureshi Jan 17 '23 at 19:51
  • 2
    Right, because `10` is hard-coded to be defined in your server side code. If you need your server side code to respect values set in the client side, then you'll need to make a server request to dynamically load this data. AJAX is the most prevalent method used to achieve this. – Rory McCrossan Jan 17 '23 at 20:01
  • 1
    @HamzaQureshi you need `$a` variable getting from controller in here `@json($a)` used like that – Jignesh Joisar Jan 17 '23 at 20:02
  • ok i understand in actual i am developing pos system where product can be in millions and if this methood works it will be the fastest for filtering thanks for every contributor – Hamza Qureshi Jan 17 '23 at 20:10
  • 1
    Of course it does; in `->where('category_id', 10)`, `10` is a hard-coded PHP value, while `var $a = 10;` is a JS value. By the time `var $a = 10;` is run, `->where()` has already attempted to execute and failed, since `$a` is not defined yet. PHP is a server side language that runs _before_ JS, which is a front-end language. Do you understand? Basically, don't try to mix and match languages like this; it doesn't work. PHP variables can be used in JS, but JS variables cannot be used in PHP (at least not the way you're trying.) – Tim Lewis Jan 17 '23 at 20:10

0 Answers0