我正在使用Laravel和Backbone开发一个系统。
用户可以查看自己的个人资料,例如电子邮件地址,姓名,DOB等
在Laravel我正在使用资源控制器(索引,创建,存储,显示,编辑,更新和销毁)
因此,如果用户想查看他们自己的个人资料,他们会访问domain.com/users/ {their ID}。
我遇到的问题是如何将{他们的ID}传递给骨干网,以便我可以将其附加到域名,这样当骨干网获取时,它可以获取他们的记录。
Backbone工作正常。如果我在其中硬编码id将获取正确的数据。
用户ID当前存储在会话中。
这里的最佳做法是什么?您如何发送骨干用户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(){
}
});
},
答案 0 :(得分:6)
在您的视图中(Laravel View
)执行以下操作:
@if(Auth::check())
<script>
var userID = "{{ Auth::user()->id }}";
</script>
@endif
现在,您可以使用userID
中的JavaScript
。您还可以创建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);
});
在master
布局中,<head>
:
<script>var userObj = {{ $userJs or 'undefined' }}</script>
因此,您始终可以在js中使用用户对象:
if(userObj) {
console.log(userObj.id);
console.log(userObj.username);
console.log(userObj.email); // all properties
}
您可以忽略toJson()
中的$user = Auth::user()->toJson();
。 Laravel
会做到这一点。