A user can subscribe to a package and the package can have many videos.
All paid videos are not visible unless the user subscribes to a 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
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
@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
public function user()
{
return $this->belongsTo(User::class);
}
public function packages()
{
return $this->hasMany(Package::class);
}
User.php model
public function subscriptions()
{
return $this->hasMany(Subscription::class);
}
Package.php model
public function subscription()
{
return $this->belongsTo(Subscription::class);
}
public function videos()
{
return $this->belongsToMany(Video::class);
}
Video.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()
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.