Print JavaScript variable value inside a php tag using blade template in Laravel

情到浓时终转凉″ 提交于 2019-12-05 15:41:48

I am afraid that what you are asking is not possible. The simple reason being JavaScript is client-side and PHP is server-side.

You can always place PHP code inside JavaScript because it will just be echoed there and won't run at that very instant. Whereas if you want to use a JavaScript variable inside PHP, that means you are trying to access a variable which doesn't even exist at the point of when the server processes the request.

Update

There is a workaround to this. You can pass the data which is needed in JS as parameters in the URL and then get these values in PHP using $_GET.

Probably its late, but I think I have solution. Your code

myUrl = "{{ action('FollowsController@show', 'id') }}" ;

is inside javascript block. Therefore the blade parser use parenthesis as javascript object rather as blade variable. So you can't use any PHP variables inside script block. In my solution I would replace your line with:

myUrl = "@include("public.default.js_values.myUrl")" ;

and then create that template file

(in your views folder)/public/default/js_values/myUrl.blade.php

and add one line into that file

{{ action('FollowsController@show', 'id') }}

This way blade parser will include the content on myUrl.blade.php. In file will correctly resolve that in parenthesis is variable and returns the value of php variable (in your case the method) back to javascript.

I have tested this in similar situation and it worked.

Just use {!! $vars !!}.

var link = {!! "'".url('string/'.$vars.'/string')."'" !!};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!