1

Evening,

I have one (maybe simple question), which I can't figure out how to do on my own. I'm using Laravel Framework version 4.

How can I check if a user is logged in within javascript? I want the menu bar to fadeout when a user scrolls 100px down, but if the user is logged in then I want it to fadeout when the user scrolls 150px down..

This is how the javascript looks like by now:

(function ($) {
$(document).ready(function(){

$(window).scroll(function() {
    var yPos = ( $(window).scrollTop() );
    if(yPos > 100) { // show sticky menu after screen has scrolled down 200px from the top
        $("#fixed_header").fadeIn(100);
        $("#fixed_header_konto").fadeIn(100);
        $("#header").fadeOut(100);
        $("#header_konto").fadeOut(100);
    } else {
        $("#fixed_header").fadeOut(100);
        $("#fixed_header_konto").fadeOut(100);
        $("#header").fadeIn(100);
        $("#header_konto").fadeIn(100);
    }
    });
  });
}(jQuery));
dinkode.dk
  • 57
  • 1
  • 12

2 Answers2

2

I believe you can do it in your view by using the following code:

@if(Auth::check())

  <script>{{ 'var logged = true;' }}</script>

@endif

That way you can check the logged value via javascript to check if the user is logged in.

tliokos
  • 3,606
  • 3
  • 28
  • 28
0

You may use a view composer to dump the logged in user data (you may just pass a flag either) directly to the JavasScript using something like this:

View::composer('layouts.master', function($view) {
    $user = null;
    if(Auth::check()) {
        $user = Auth::user();
    }
    $view->with('authUser', $user);
});

Your master layout:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script>var userObj = {{ $authUser or 'undefined' }}</script>
    </head>
    <body>
        <!-- content -->
    </body>
</html>

Now, you may able to check if the user is logged in or not by using something like this:

<script>
  $(function(){
    if(userObj) console.log(userObj);
  });
</script>

This is from my last article written on march 6th March, 2014 on Heera.IT, check the article for more detailed explanation. Also, you may don't need to dump the whole user object but it's fine.

The Alpha
  • 143,660
  • 29
  • 287
  • 307