Reputation: 1347
I have below code, $tables contains all tables available in the system and $order_info contains all current orders, that contains table_id as well,
Now I want to show only those tables which table_id is not in $order_info array.
@foreach($tables as $t)
@foreach($order_info as $o)
@if($o['table_id'] != $t->table_id)
<option value="{{$t->table_id}}">{{$t->table_number}}</option>
@endif
@endforeach
@endforeach
obviously above code is showing me duplicate table numbers because I am looping it for two arrays, How can I show only those tables which are not in $order_info
Thank you,
Upvotes: 0
Views: 125
Reputation: 5623
It can be easier to perform that in the Controller
directly
I supposed you have Two Models Order
and Table
and you have define relation between those two models like this
class Table extends Model {
public function oders(){
return $this->hasMany('Order');
}
}
class Order extends Model {
public function table(){
return $this->belongsTo('Table');
}
}
So in the controlle which render the view
in which you perform the loop you can render order like this
public function ...() {
$order_info = Order::where('...', '')->get();
$tables = Table::whereDoesntHave('order', function($query){
$query->whereNotIn('id', $order_info->pluck('id'));
});
return view('...', compact('tables', 'order_info');
}
Here as you have already list of order_info
you can return only table which order with a given id
doesn't exist like this
$tables = Table::whereDoesntHave('order', function($query){
$query->whereIn('id', $order_info->pluck('id'));
});
Here I use pluck
to return an array of id
of orders
in the order_info
table.
Upvotes: 2
Reputation: 1347
Thanks friends for help, Found some easy way in Laravel,
@foreach($tables as $t)
@if (! $order_info->contains('table_id', $t->table_id))
<option value="{{$t->table_id}}">{{$t->table_number}}</option>
@endif
@endforeach
Upvotes: 2
Reputation:
actually it will not return duplicate. first loop
@foreach($tables as $t)
@endforeach
it will return a value then second loop will start it will compare the previous single value with all the values from order_info. . again first loop will return a value. then 2nd loop will iterate for each individual value returned by the first loop .
Upvotes: 0
Reputation: 380
You have to write your code like this -
@foreach($tables as $item)
@if(! in_array($item->table_id,array_column($order_info,'table_id')))
<option value="{{$item->table_id}}">{{$item->table_number}}</option>
@endif
@endforeach
or
@foreach($tables as $item)
@if(array_search($item->table_id, array_column($order_info,'table_id')) == false)
<option value="{{$item->table_id}}">{{$item->table_number}}</option>
@endif
@endforeach
Upvotes: 2