[英]Filtering search results in laravel
A user can subscribe to a package and the package can have many videos.用户可以订阅 package 和 package 可以有很多视频。
All paid videos are not visible unless the user subscribes to a package.除非用户订阅 package,否则所有付费视频均不可见。
Please Note: The free videos are visible without subscription.请注意:免费视频无需订阅即可观看。
My problem is that when I want to apply search queries the user can view all the videos, which I don't want, I want the user to view only the videos he subscribed for.我的问题是,当我想应用搜索查询时,用户可以查看我不想要的所有视频,我希望用户只查看他订阅的视频。
Here is my code lines:这是我的代码行:
VideoController.php视频控制器.php
public function index(Request $request)
{
$keyword = $request->get('search');
$perPage = 10;
if (!empty($keyword)) {
$videos = Video::where('video_title', 'LIKE', "%$keyword%")
->orWhere('video_file', 'LIKE', "%$keyword%")
->latest()->paginate($perPage);
} else {
$videos = Video::where('video_type', '=', 'Free')->latest()->paginate($perPage);
}
return view('video.index', compact('videos'));
}
video/index.blade.php视频/index.blade.php
@foreach (auth()->user()->subscriptions as $subscription)
@foreach ($subscription->packages as $package)
<h4>
{{ $package->package_name }}
</h4>
@foreach ($package->videos as $video)
<a href="{{ url('/video/' . $video->id) }}">
{{ $video->video_title }} (Click to view)
</a>
@endforeach
@endforeach
@endforeach
@foreach ($videos as $item)
<a href="{{ url('/video/' . $item->id) }}">
{{ $item->video_title }} (Click to view)
</a>
@endforeach
<div> {!! $videos->appends(['search' => Request::get('search')])->render() !!} </div>
Subscription.php model订阅。php model
public function user()
{
return $this->belongsTo(User::class);
}
public function packages()
{
return $this->hasMany(Package::class);
}
User.php model用户.php model
public function subscriptions()
{
return $this->hasMany(Subscription::class);
}
Package.php model Package.php model
public function subscription()
{
return $this->belongsTo(Subscription::class);
}
public function videos()
{
return $this->belongsToMany(Video::class);
}
Video.php model视频.php model
public function packages()
{
return $this->belongsToMany(Package::class);
}
So instead of checking for only keyword, you will have to add another clause that checks for subscription of the current user.因此,您必须添加另一个子句来检查当前用户的订阅,而不是只检查关键字。
$videos = Video::whereHas('packages.subscription', function($query) {
$query->where('subscription.user_id', auth()->id());
})
->where(function($query) use ($keyword) {
$query->where('video_title', 'LIKE', "%$keyword%")
->orWhere('video_file', 'LIKE', "%$keyword%");
})
->latest()
->paginate($perPage);
whereHas
will check whether video has a subscription and subscription's user_id is the same as current user id ( auth()->id()
). whereHas
将检查视频是否有订阅,并且订阅的 user_id 与当前用户 id ( auth()->id()
) 相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.