laravel 在整数上调用成员函数 follow()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36889606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function follow() on integer
提问by GarethFrazer
I am trying to save users to a followers table when one user follows another. When I try to get one user to follow another I get
当一个用户关注另一个用户时,我试图将用户保存到一个关注者表中。当我试图让一个用户关注另一个用户时,我得到
Call to a member function follow() on integer
在整数上调用成员函数 follow()
whenever I try to follow another user.
每当我尝试关注另一个用户时。
Follow Button/Form
关注按钮/表单
{!! Form::open(['route' => 'follow_user']) !!}
{!! Form::hidden('id', $user->id) !!}
<button type="submit" class="btn btn-primary">Follow {{$user->name}}</button>
{!! Form::close() !!}
Route
路线
Route::post('/follow', [
'as' => 'follow_user', 'uses' => 'FollowersController@store'
]);
Followers Controller
追随者控制器
public function store()
{
$user1 = Auth::user()->id;
$user2 = Input::get('id');
$user1->follow($user2);
return redirect()->action('HomeController@index');
}
Methods I am using in User model
我在用户模型中使用的方法
function followers()
{
return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');
}
function follow(User $user) {
$this->followers()->attach($user->id);
}
function unfollow(User $user) {
$this->followers()->detach($user->id);
}
回答by Alexey Mezenin
You're trying to run follow()
on a ID, not the User object (as you probably want).
您试图follow()
在 ID上运行,而不是在 User 对象上运行(如您所愿)。
This returns an integer:
这将返回一个整数:
$user1 = Auth::user()->id;
Maybe you want something like this:
也许你想要这样的东西:
$user1 = Auth::user();
$user2 = Input::get('id');
$user1->follow(User::find($user2));
Thanks to @blackpla9ue for the fix.
感谢@blackpla9ue 的修复。