Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current user in Javascript/jQuery Laravel 5.1

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

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

like image 422
Chaudhry Waqas Avatar asked Sep 04 '15 12:09

Chaudhry Waqas


2 Answers

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

  1. Install laracasts/utilities by 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>
    

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.

like image 95
Aditya Giri Avatar answered Oct 29 '22 08:10

Aditya Giri


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

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

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

And use the user var in your js file.

EDIT:

As per Mark's comment this is indeed cleaner:

<script>
  var user = {!! auth()->user()->toJson() !!};
</script>
<!-- include your js file  here-->
like image 32
Roboroads Avatar answered Oct 29 '22 08:10

Roboroads