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

6
  • 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. Commented Jan 17, 2023 at 19:01
  • but where works fine if i use where('category_id' , 10) Commented Jan 17, 2023 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. Commented Jan 17, 2023 at 20:01
  • 1
    @HamzaQureshi you need $a variable getting from controller in here @json($a) used like that Commented Jan 17, 2023 at 20:02
  • 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.) Commented Jan 17, 2023 at 20:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.