Expression Expected Window.Laravel.userId =
I am building an app using Laravel, Vuejs and editor 'PHPstorm'
I wrote following code in my app.blade.php file inside <head></head>
tag
@if(!auth()->guest()) <script type="text/ecmascript-6"> window.Laravel.userId = <?php echo auth()->user()->id; ?> </script> @endif </head> <body>
it is showing 'expression expected' error in phpstorm.
what is the solution for that?
(note new updations of my question) then My next question is that I want to use this in my app.js file
console.log(window.Laravel.userId)
if(window.Laravel.userId){
is the above code is the right way to use it in .js file or there is a better solution??
(new update) My code
Here I add my code app.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link target="_blank" rel="nofollow noreferrer" href="{{ asset('css/app.css') }}" rel="stylesheet">
<script type="text/ecmascript-6">
window.Laravel = '<?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>'
</script>
@if(!auth()->guest())
<script>
window.Laravel.userId = '<?php echo auth()->user()->id; ?>'
</script>
@endif
</head>
<body>
<div id="app">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<!-- Collapsed Hamburger -->
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Branding Image -->
<a class="navbar-brand" target="_blank" rel="nofollow noreferrer" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
</div>
<div class="collapse navbar-collapse" id="app-navbar-collapse">
<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
</ul>
<!-- Right Side Of Navbar -->
<ul class="nav navbar-nav navbar-right">
{{--add code here extra for notification--}}
@if(Auth::check())
<lesson v-bind:lessons="lessons"></lesson>
@endif
<!-- Authentication Links -->
@guest
<li><a target="_blank" rel="nofollow noreferrer" href="{{ route('login') }}">Login</a></li>
<li><a target="_blank" rel="nofollow noreferrer" href="{{ route('register') }}">Register</a></li>
@else
<li class="dropdown">
<a target="_blank" rel="nofollow noreferrer" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a target="_blank" rel="nofollow noreferrer" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
@endguest
</ul>
</div>
</div>
</nav>
@yield('content')
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
app.js
require('./bootstrap');
window.Vue = require('vue');
window._=require('lodash');
window.$=window.jQuery =require('jquery');
Vue.component('lesson', require('./components/LessonNotification.vue'));
const app = new Vue({
el: '#app',
data:{
lessons:''
},
created(){
console.log(window.Laravel.userId);
if(window.Laravel.userId){
axios.post('/notification/lesson/notification').then(response => {
this.lessons=response.data;
console.log(response.data)
});
Echo.private('App.User.'+window.Laravel.userId).notification((response) =>{
data={"data":response};
this.lessons.push(data);
});
}
}
});
The main task of code
Actually, My code's main theme or task is that I want to use or get the logged-in user information in any scripts specially .js file. That's why First I set up or define logged user info .. the following code in app.blade.php
@if(!auth()->guest()) window.Laravel.userId = user()->id; ?> @endif
Then since I need logged-in user id .so I called it by the following code in app.js
console.log(window.Laravel.userId)
My answer from @vivek_23
<script type="text/ecmascript">
window.Laravel = JSON.parse('<?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>');
</script>
<!-- This makes the current user's id available in javascript -->
@if(!auth()->guest())
<script>
window.Laravel.userId = '<?php echo auth()->user()->id; ?>'
</script>
@endif
Answer
Add single quotes in your expression or I would suggest you to better use interpolation {{}}
which Laravel blade syntax provides.
<script type="text/ecmascript-6">
window.Laravel = {{ json_encode(['csrf_token' => csrf_token()]) }};
</script>
@if(!auth()->guest())
<script type="text/ecmascript-6">
window.Laravel.userId = {{ auth()->user()->id }};
</script>
@endif
#Update:
<script type="text/ecmascript-6">
window.Laravel = '<?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>'
</script>
Your code above has a string(JSON string) in window.Laravel
and not a JSON object. You could do an additional JSON.parse() to make it a JSON object as below.
<script type="text/ecmascript">
window.Laravel = JSON.parse('<?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>');
</script>
Now, you are trying to get logged-in user ID.
<script>
window.Laravel.userId = '<?php echo auth()->user()->id; ?>'
</script>
This code above would work as is because we have fixed type of window.Laravel
from JSON string
to object
.
But best is to keep it as integer/number itself.
<script>
window.Laravel.userId = <?php echo auth()->user()->id; ?>;
</script>
Suggestion:
Since you are using Laravel framework, it's better to always go with Laravel blade syntax than dealing with PHP tags. So, it would change your code snippets as below:
<script type="text/ecmascript">
window.Laravel = {!! json_encode(['csrfToken' => csrf_token()]) !!};
</script>
<script>
window.Laravel.userId = {{ auth()->user()->id }};
</script>
Notice the use of {!! !!}
instead of {{ }}
. This is because when you use normal interpolation, Laravel automatically escapes string content to prevent XSS attacks by passing it via htmlspecialchars(). We need to use {{}}
if we are trying to print any user supplied information. In your case, you are generating a csrf token and sending token to client side. Hence, it is safe to print data unescaped.
More information is here.
Since Laravel 5.5
, we can directly use the @json
blade directive.
<script type="text/ecmascript">
window.Laravel = @json([
'csrfToken' => csrf_token()
]);
</script>
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms