问题描述
这是我的用户。刀片:
@extends('layouts.app')
@section('users')
<table class="table">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Ad</th>
<th scope="col">Email</th>
<th scope="col">Səlahiyyət</th>
<th scope="col">Post sayı</th>
<th scope="col">Düzəlişlər</th>
</thead>
<tbody>
@foreach ($users as $user )
<tr>
<th scope="row">{{$user->id}}</th>
<h4 class="media-heading"> <td><a href="posts/{{$user->id}}" class="anchor-username">{{$user->name}} </a></td></h4>
<td>{{$user->email}}</td>
<td>{{$user->getRoles['name']}}</td>
<td>{{$user->getPost['user_id']}}</td>
<td><a href="{{route('delete',['id'=>$user->id])}}">Sil</a><br><a href="{{route('edit',['id'=>$user->id])}}">Düzəlt</a></td>
@endforeach
</tbody>
</table>
@endsection
这是我的控制器
public function index($id)
{
$posts = Post::where('user_id',$id)->get();
return view('posts',compact('posts'));
}
我的用户模型:
public function getRoles()
{
return $this->hasOne('App\Role','id','role_id');
}
public function getPost()
{
return $this->hasOne('App\Post','user_id','id');
}
解决方法
// Controller
public function index()
{
if(Auth::check() && Auth::user()->role->id == 2) {
$posts = Auth::user()->posts()->latest()->get();
return view('user.post.index',compact('posts'));
}
else{ return view('login');
}
}
// View
<span class="btn btn-warning sm">{{ $posts->count() }}</span>
// User Model
public function posts()
{
return $this->hasMany('App\Post');
}
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}
,
由于您的控制器中包含以下内容:$posts = Post::where('user_id',$id)->get();
您可以在自己的视图中执行此操作:<td>{{ $posts->count() }}</td>
但是,我建议按照Md.Azizur Rahman的建议使用雄辩的关系。
-
您的模型在
hasMany
中应具有getPost
关系(应重命名为getPosts
或只是posts
IMO)。public function posts() { return $this->hasMany('App\Post'); }
-
另外,请确保您的帖子模型与您的用户模型之间存在
belongsTo
关系!public function user() { return $this->belongsTo('App\User'); }
-
然后您可以从控制器中替换以下内容:
$posts = Post::where('user_id',$id)->get(); return view('posts',compact('posts'));
具有:
return view('posts');
-
最后,该视图将如下所示:
<td>{{ $user->posts->count() }}</td>
*(posts是关系的名称)或者:
<td>{{ auth()->user()->posts->count() }}</td>
用于经过身份验证的用户(我认为您不会使用它,因为我认为您在示例中正在执行admin CRUD之类的事情)。
希望有帮助!