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.
As per looking at the standard and the way most javascript templates engine work, I would prefer to do something like this:
laracasts/utilities by using composer require laracasts/utilities
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');
}
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.
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-->
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With