调用未定义的方法(laravel 5.2) [英] Call to undefined method (laravel 5.2)
问题描述
我想显示用户的朋友.但我收到以下错误:
I want to display friends of the user. But I am getting the following error:
Builder.php第2345行中的BadMethodCallException:调用未定义 方法Illuminate \ Database \ Query \ Builder :: friends()
BadMethodCallException in Builder.php line 2345: Call to undefined method Illuminate\Database\Query\Builder::friends()
FriendController:
FriendController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use Auth;
class FriendController extends Controller
{
public function getIndex(){
$friends=Auth::user()->friends();
return view('friends',['friends'=>$friends]);
}
}
路线:
Route::get('/friends',[
'uses' => 'FriendController@getIndex',
'as' => 'friends',
'middleware' => 'auth:web'
]);
用户模型:
public function getName(){
if($this->firstname && $this->lastname){
return "{$this->firstname} {$this->lastname}";
}
if($this->firstname)
return $this->firstname;
return null;
}
public function getNameOrUsername(){
return $this->getName() ?: $this->username;
}
public function getFirstNameOrUsername() {
return $this->firstname ?: $this->username;
}
我的观点:
<div id="grp" class="panel-heading">
<h3 id="grouptitle" class="panel-title">Your Friends</h3>
@if(!$friends->count())
<p>you have no friends</p>
@else
@foreach($friends as $user)
@include('userblock')
@endforeach
@endif
</div>
userblock.blade:
userblock.blade:
<div class="media">
<a href="{{ route('myplace', ['username'=>$user->username]) }}" class="pull-left">
<img src="" class="media-object" alt="{{ $user->getNameOrUsername() }}">
</a>
<div class="media-body">
<h4 class="media-heading"><a href="#">{{ $user->getNameOrUsername() }}</a></h4>
</div>
推荐答案
您似乎在user
模型中作为用户与其好友(再次是用户)之间存在许多关系.因此,我们可以使用Users
检索所选用户的朋友.
为此,请将以下功能添加到您的User
模型中.
It seems like you are having many to many relationship between user
model as user and its friends(again a user).So, we can use belongsToMany()
method to retrieve the friends of selected user as Users
.
To do so, add the following function to your User
model.
public function friends(){
return $this->belongsToMany('App\User::class','friends','user_id','friend_id')->withPivot('accepted');
}
要获取当前登录用户的朋友,请使用以下命令:
To get the friends of currently loged in User use following:
$friends = Auth::user()->friends()->get();
这篇关于调用未定义的方法(laravel 5.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!