MJ DEV
MJ DEV

Reputation: 704

get auth user into vuejs object

i want to get my current logged user details into my hidden input fields. so i write input values like this

<input type="hidden" name="name" v-model="comment.name">
<input type="hidden" name="avatar" v-model="comment.avatar">

or i want to get directly user informations into my vuejs objects

comment: {                  
          name: '',
          avatar: '',
          user_id: '',
          comment: '',
          status: 'Approved',
          created_at: ''
        },

how i get current logged user details into this object. i used this fetch method to get details

axios.get("api/userdetails").then(({ data }) => (this.users.fill(data)));

this is my controller

return auth('api')->user();

Upvotes: 0

Views: 4962

Answers (3)

Haron
Haron

Reputation: 2619

How to get current authenticated user id using Vuejs and Laravel

You Should add to <meta name="user-id" content="{{ Auth::user()->id }}"> in

// app.blade.php or whatever you have maybe master.blade.php like below

    <head>
        <meta charset="UTF-8">
        @if (Auth::check()) 
          <meta name="user-id" content="{{ Auth::user()->id }}">
        @endif 
        <meta http-equiv="X-UA-Compatible" content="IE=edge" 
      ...
      ..

Then in the app.js or main.js add

 data: {
    comment: {
      name: '',
      cart: '',
      user_id: document.querySelector("meta[name='user-id']").getAttribute('content'),
    },

// Finally in your MyVueComponent.vue

<div class="col-sm-6">
    <label>First Name *</label>
    <input type="text" v-model="comment.name" class="form-control" required>
    <input type="hidden" v-model="comment.cart">
    <input type="hidden" v-model="comment.user_id">
</div>

hope will help someone

Upvotes: 2

Skytek
Skytek

Reputation: 1

If i understood this well, this.users is list of all users you have in your, let's say, state? If this is true, then you have to recognize your currently logged user by some unique id he has, maybe you should use this.users.filter to find that user and compare id with currently logged user. Then just grab field you need to fill.

Upvotes: 0

Dan
Dan

Reputation: 102

Why not just pass the user variables straight into the blade template in the vuejs object?

{{ Auth::user()->id }} {{ Auth::user()->name }} {{ Auth::user()->avatar }}

Etc

Upvotes: 0

Related Questions