[英]Call to undefined method (laravel 5.2)
我想顯示用戶的朋友。 但是我收到以下錯誤:
Builder.php第2345行中的BadMethodCallException:調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: friends()
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:
<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
模型作為用戶與它的朋友(再次是用戶)之間有很多關系。因此,我們可以使用belongsToMany()
方法來檢索選定用戶作為Users
的朋友。
這樣做,將以下功能添加到您的User
模型。
public function friends(){
return $this->belongsToMany('App\User::class','friends','user_id','friend_id')->withPivot('accepted');
}
要獲得當前登錄用戶的朋友,請使用以下命令:
$friends = Auth::user()->friends()->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.