Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery.

Specifically, I want to make changes to my CSS when a user is logged in. By default:

body{
    background: url('image.jpg');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}

If the user is logged in, I want my CSS to be updated as follows:

body{
    /*Nothing*/
}

I attempted something in my js file:

var loggedIn={!! json_encode(Auth::check()) !!};
if(loggedIn)
    alert('Logged In as user!');

However, the above code did not produce the desired result. I require assistance. If there is an alternative method that can achieve my goal, please advise.

Thank you

Answer №1

Give this a shot.

const isLoggedIn = {{ auth()->check() ? 'yes' : 'no' }};
if (isLoggedIn)
    console.log('Currently logged in as user!');

Answer №2

To ensure seamless integration with your template, consider inserting the following script block:

    <script>
        var UserAuth = "{{{ (Auth::user()) ? Auth::user() : null }}}";
    </script>

This will allow you to easily access the UserAuth variable in your javascript code.

Answer №3

To enhance the existing window.Laravel definition in Laravel, we can simply add to it by including the following script in the head of the master template:

<script>
    window.Laravel = {
        csrfToken: '{{csrf_token()}}',
        auth: {
            user: auth()->user()
        }
    }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize a script to interact with CasperJS

When it comes to running my CasperJS script, I typically do so from the command line interface using this command: casperjs --ignore-ssl-errors=true --ssl-protocol=any scrape.js In order to fully automate the process, I am now looking into calling the sc ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

"Create a New Browser Tab When User Interacts with a Hyperlink leading to an External Website

I am currently working on a recommendations app built with React and I want to enable users to navigate to external websites when they click on a component that displays information about that website. At the moment, I have implemented a wrapper that, upo ...

Trigger ng-change event for each dropdown selection made in AngularJS

Currently, I have a dropdown menu that allows users to select a report for generation. When a user picks a report from the dropdown, it generates and downloads the report for mobile viewing. By utilizing ng-change, the system only detects when a user wants ...

The server experiences crashing issues when attempting to retrieve data from Mangodb for the second or third time

This is the code I have written in VS Code. const express=require("express"); const app= express(); const mongoose=require("mongoose"); const Listing=require("./models/listings"); const path=require("path"); const me ...

Can JavaScript be used to update/override Prototype version 1.4 to version 1.7 on a different website?

(I'm uncertain about the best way to phrase this question, feel free to make changes). I am in the process of embedding a JS widget onto a different website that is using Prototype.js Version 1.4. I have incorporated jQuery into my widget and have it ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle. I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structur ...

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

GWT Validation - Enhance Your Application with a Third Party Library

Is there a reliable JavaScript library available for validating GWT fields such as Email, Text Length, Phone Number, Date & SSN, etc.? I am unable to use the GWT Validation Framework or GWT Errai in my application because I receive responses as JSON r ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

Utilizing Jquery tabs for consistent height display

Currently, I am utilizing jquery tabs for showcasing various content. This is what my functions look like: $(function() { $( "#tabs" ).tabs(); }); I attempted to ensure all tabs have the same height by using this approach: var heightStyle = ...

Is there a way to generate a hierarchical list menu using strings?

Within an HTML Application (HTA), I am utilizing vbscript to retrieve a list of subnet locations which is output as text in the following format: Chicago Denver Dallas Dallas/North Dallas/South Dallas/West Dallas/West/Building1 Dallas/West/Bu ...

Is there a way to retrieve data from three different Bookshelf.js models in a single query?

Three tables are in my database: User, UserDrink, and VenueDrink Here is a preview of the sample data: User id | name | gender | -------------------- 1 | John | male | 2 | Jane | female | UserDrink id | count | user_id | venue_drink_id 1 | 3 | ...

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Ember Data's counting model feature

After searching through numerous examples on Stackoverflow, I am still struggling to grasp the concept of how get('length') functions. I am attempting to retrieve a user count in the helper model. The issue may lie in my approach to using get(&a ...

Embark on the journey of incorporating the Express Router

My Nodejs server is set up with router files that use absolute routes for the HTTP methods, such as /api/users/all. // /routes/user.routes.js module.exports = (app) => { app.use((req, res, next) => { res.header( "Access-Control-All ...

Is there a way to prevent Backbone.js from deleting surrounding elements with 'default' values?

Trying to articulate this question is a challenge, so please let me know if further clarification is needed. As I am new to backbone.js, my inquiry may seem basic. My goal is to utilize backbone to efficiently generate graphs using the highcharts library. ...