在 Javascript/jQuery Laravel 5.1 中获取当前用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32398505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:18:09  来源:igfitidea点击:

get current user in Javascript/jQuery Laravel 5.1

javascriptjquerylaravel

提问by Chaudhry Waqas

How I can get the current user in JS/Jquery? In the blade we can do like

如何在 JS/Jquery 中获取当前用户?在刀片中,我们可以这样做

{{Auth::user()}}But it wont work in the .js file.

{{Auth::user()}}但它不会在 .js 文件中工作。

回答by Aditya Giri

As per looking at the standard and the way most javascript templates engine work, I would prefer to do something like this:

根据标准和大多数 javascript 模板引擎的工作方式,我更愿意做这样的事情:

  1. Install laracasts/utilitiesby using composer require laracasts/utilities
  2. In the controller method, from where you are returning view, I would make it look like this:

    public function returnUser(){
        $user = Auth::user();
        Javascript::put([ 'user.name' => $user->name, 'email' => $user->email ]);
        return view('my.user.js');
    }
    
  3. In the blade file, I would simply do,

    <script>alert("Hi " + user.name + ". Your email is " + user.email)</script>
    
  1. laracasts/utilities使用安装composer require laracasts/utilities
  2. 在控制器方法中,从您返回视图的位置,我会使其看起来像这样:

    public function returnUser(){
        $user = Auth::user();
        Javascript::put([ 'user.name' => $user->name, 'email' => $user->email ]);
        return view('my.user.js');
    }
    
  3. 在刀片文件中,我会简单地做,

    <script>alert("Hi " + user.name + ". Your email is " + user.email)</script>
    

And yeah, I would even prefer the way, @Robbin said. And yeah just one more edit to his answer, in laravel 5.1, Auth::user()should not be used. It should be used as auth()->user() //->name or ->email or ->anything.

是的,我什至更喜欢这种方式,@Robbin 说。是的,在 laravel 5.1 中,对他的答案再进行一次编辑,Auth::user()不应该使用。它应该用作auth()->user() //->name or ->email or ->anything.

回答by Roboroads

You have to build an API and get it with AJAX. You cannot use blade in javascript files.

您必须构建一个 API 并使用 AJAX 获取它。您不能在 javascript 文件中使用刀片。

Or, in the <head>of your template, you place.

或者,在<head>您的模板中,您放置。

<script>
  var user = {!! json_encode((array)auth()->user()) !!};
</script>
<!-- include your js file  here-->

And use the user var in your js file.

并在您的 js 文件中使用用户 var。