I have to two eloquent returned arrays :
$services = \App\Service::all();
$userService = \App\UserService::where('user_id', Auth::user()->id)->get();
What i tried is that :
@foreach($services as $service){
@foreach($userServices as $userService){
@if($userService->service_id != $service->id)
<option value="{{ $service->id }}">{{ $service->name }}</option>
@endif
@endforeach
@endforeach
But its repeating the options, And creating mess.
What will be a good approach ?
You can try this out:
$userServices = \App\UserService::where('user_id', Auth::user()->id)
->pluck('service_id')->toArray();
$services = \App\Service::whereNotIn('id',$userServices)->get();
//Now you can loop through services
@foreach($services as $service){
<option value="{{ $service->id }}">{{ $service->name }}</option>
@endforeach
Hope it helps...
You need to use nested relations in your model. Like this;
class Service extends Model
{
public function user_service()
{
return $this->hasMany(UserService::class, 'user_id');
}
}
And Controller
$user_id = Auth::user()->id;
$services = Service::with(['user_service' => function ($query) use ($user_id) {
$query->where('user_id', $user_id);
}])->get();
return view('page', compact('services'));
i have read the code
$services = \App\Service::all();
$userService = \App\UserService::where('user_id', Auth::user()->id)->get();
and
@foreach($services as $service){
@foreach($userServices as $userService){
@if($userService->service_id != $service->id)
<option value="{{ $service->id }}">{{ $service->name }}</option>
@endif
@endforeach
@endforeach
Userservice is sufficient to what you want to do, no need to retrieve data twice. you can simply find all service for the logged user in you query $user_id = Auth::user()->id;
return Service::with(['user_service' => function ($query) use ($user_id) {
$query->where('user_id', $user_id);
}])->get();
or try to make a inner joins with raw query.
If you don't want to change your approach just change !=
to ==
@if($userService->service_id == $service->id)
Or if you want a good approach try eloquent.
Your models seems to be many to many relationship
Visit this link https://laravel.com/docs/5.4/eloquent-relationships#many-to-many