1

I have defined a jQuery variable

var user_id = parseInt($(this).attr('id').replace(/[^\d]/g, ''));

and i want to get the user name like this:

alert({!! \App\User::findOrFail(user_id)->name !!});

Is this even possible?

i get this error:

enter image description here How can i get the user name through jQuery variable??

update

i did this

var user_id = parseInt($(this).attr('id').replace(/[^\d]/g, ''));
{{ var_dump($user_id) }}

and i get this error:

enter image description here

4
  • in laravel blade template you used some thing like this ..... alert({{$test->name}});... and its working Commented Mar 13, 2017 at 9:23
  • yes but this is dynamic, so I can't fix the variable because there are a lot of different users Commented Mar 13, 2017 at 9:25
  • Possible duplicate of How to use JavaScript variable in PHP? Commented Mar 13, 2017 at 9:30
  • i can't solve my problem with that question Commented Mar 13, 2017 at 9:33

2 Answers 2

1

You should pass your user data from the controller to the view. In the view you can pass is to your javascript.

Example:

In your controller

$userName = \App\User::findOrFail(user_id)->name; return view('blade...', ['user_name' => $userName);

In your blade

<script>var userName = '{{ $userName }}' </script>

If you need more information about the user, you can pass the user to the blade and call the name like so: `{{ $user->name }}.

If the user is dynamic you can maybe look to make a simple api-like-endpoint to load the data of the user.

Sign up to request clarification or add additional context in comments.

3 Comments

yes i know I can return a view with php variable, but I need somehow to get PHP inside view to work with javascript variable...
I don't think it works the other way around. You can't make php work with javascript-variables. PHP is handled on the server-side and javascript on the client-side.
Yes, you were right this is not possible and all of your answers are wrong....this can only be done with ajax!!!
1

You can implement it in view. Something like this

<script> var name = <?php echo \App\User::findOrFail($user_id)->name ?>
</script>

And then use name variable in your javascript, offcorse yous shold at first get $user_id.

2 Comments

Yess that is exactly what i am trying to do....and my question is how can i get the $user_id from a html div id? Actually i get the variable...but i can't work with it because blade doesn't see that variable
For example you can save it in url, or in cookie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.