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(){
}
});
},
In your view (
Laravel View
) do something like this:Now you can use the
userID
in yourJavaScript
. You may also create a View Composer:In your
master
layout, between<head>
:So, you can always use the user object in js:
Update:
You can omit the
toJson()
from$user = Auth::user()->toJson();
.Laravel
will do it.