PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

[FIXED] How can I use auth on vue component ? (Vue.JS 2)

 September 04, 2022     authentication, laravel-5.3, vue-component, vue.js, vuejs2     No comments   

Issue

My view blade like this :

@if (Auth::user())
    <favorite :id="{{ $store->id }}"></favorite>
@else
    <a href="{{url('/login?red='.Request::path())}}" class="btn btn-block btn-success">
        <span class="fa fa-heart"></span>Favorite
    </a>
@endif

Auth::user() works

But, when I try on vue component like this :

<template>
    ...
    <div v-if="Auth::user()">
        <favorite :id="item.id"></favorite>
    </div>
    <a v-else href="javascript:" class="btn btn-block btn-success">
        <span class="fa fa-heart"></span>Favorite
    </a>
    ...
</template>

<script>
    export default {
        props: ...
        computed:{
            ...
        },
        ...
    }
</script>

It does not works

There exist error like this :

invalid expression: v-if="Auth::user()"

How can I use auth on vue component ?


Solution

  1. You cannot use Laravel variables (PHP) inside your Vue this way.
  2. You should decide whether you want to build standard app or SPA.
  3. If you want to build standard multipage app, you can place your VueJS components between PHP tags exactly as you do in your first example.
  4. If you still want to build standard multipage app but be able to use your Auth::user() value, there is an option for you in point 5.
  5. Pass value of Auth::user() to the VueJS component as prop.

https://v2.vuejs.org/v2/guide/components.html#Props

Use the prop like that:

props: ['auth'],
(...)
<template>
    ...
    <div v-if="auth">
        <favorite :id="item.id"></favorite>
    </div>
    <a v-if="!auth" class="btn btn-block btn-success"> // avoid using v-else as per VueJS docs
        <span class="fa fa-heart"></span>Favorite
    </a>
    ...
</template>

and use your component in the code like: <favorite :id="{{ $store->id }}" auth="Auth::user()"></favorite>

Not sure if you don't have to cast Auth::user() to string/int but I am pretty sure you will figure it out with php.



Answered By - Marek Urbanowicz
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,204,912

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing