Laravel. How to get/pass logged in users ID in Bac

2019-05-11 08:57发布

I'm developing a system in Laravel and Backbone.

The user can view their own profile eg, email address, Name, DOB, etc

In Laravel I am using the Resource Controller (index, create, store, show, edit, update and destroy)

So if the user would like to view their own profile they would go to domain.com/users/{their ID}.

The issue I am having is how do I pass {their ID} to backbone so I can append it to the domain name so when backbone fetches it can fetch their record.

Backbone is working fine. If I hardcode the id in it will grab the correct data.

The user ID is currently stored in the session.

What is the best practice here? How are you suppose to send backbone the User ID.

Backbone Model/profile.js

    var Profile = Backbone.Model.extend({   
     urlRoot: domain + "/users",
    initialize: function () {
        this.profile = new ProfileCollection();
    }   
}),

ProfileCollection = Backbone.Collection.extend({

    initialize: function(models, options = {}) {
        this.id = options.id;
    },
    url: function() {
        return domain + "/users/" + this.id;
    }, 
    model: Profile,

});


return {
    Profile: Profile,
    ProfileCollection: ProfileCollection
}

Backbone View/profile.js

    var ProfileView = Backbone.View.extend({

    el: '.page',
    initialize: function() {
        self = this;        
        profile = new Profile.Profile;  
        profileCollection = new Profile.ProfileCollection([], { id: 453445 });
    },


    render: function(){

        profileCollection.fetch({
            success : function(){       
            }
        });
    },

1条回答
贼婆χ
2楼-- · 2019-05-11 09:26

In your view (Laravel View) do something like this:

@if(Auth::check())
    <script>
        var userID = "{{ Auth::user()->id }}";
    </script>
@endif

Now you can use the userID in your JavaScript. You may also create a View Composer:

// You may keep this code in your filters.php file
View::composer('layouts.master', function($view) {
    $user = null;
    if(Auth::check()) {
        $user = Auth::user()->toJson();
    }
    $view->with('userJs', $user);
});

In your master layout, between <head>:

<script>var userObj = {{ $userJs or 'undefined' }}</script>

So, you can always use the user object in js:

if(userObj) {
    console.log(userObj.id);
    console.log(userObj.username);
    console.log(userObj.email); // all properties
}

Update:

You can omit the toJson() from $user = Auth::user()->toJson();. Laravel will do it.

查看更多
登录 后发表回答