Reputation: 3
I have a little problem here: I want to only output things, if there are entries in the database table. Right now my code looks like this:
foreach ($customers as $customer) {
if ($customer->CURRENT_ROWNAME != NULL) {
//output stuff e.g.
<p>ID: {{$customer->customer_id}}</p>
<p>E-Mail: {{$customer->email}}</p>
<p>Phone: {{$customer->phone}}</p>
<p>Mobile: {{$customer->mobile}}</p>
else {
//do not output stuff
}
}
I THOUGHT I should search for something that outputs the name of the current field, so that it skips empty entries, like, if there is no mobile number in the table, then do not output that. So my logic is flawed right from the start. That lead me to a rather unbeautiful "solution":
@foreach ($customers as $customer)
<h2>{{$customer->name}} | {{$customer->company}}</h2>
<div class="column-left">
<p>ID: {{$customer->customer_id}}</p>
<p>E-Mail: {{$customer->email}}</p>
<p>Phone: {{$customer->phone}}</p>
@if($customer->mobile != NULL)
<p>Mobile: {{$customer->mobile}}</p>
@else
@endif
</div>
@endforeach
So this does work. But theoretically, I would need to do this manually to every database entry, where I am not exactly sure, if that field could be blank or not.
Is there a better solution to this?
Upvotes: 0
Views: 78
Reputation: 28
I think you can use array_filter
:
<?php
$data = array(
0 => array(
'name'=> '',
'company'=>'companyName',
'customer_id'=> 123456,
'phone'=> '11111',
),
1 => array(
'name'=> 'Tom',
'company'=>'',
'customer_id'=> 123457,
'phone'=> '11112',
),
2 => array(
'name'=> 'Daniel',
'company'=>'companyName',
'customer_id'=> '',
'phone'=> '11113',
),
3 => array(
'name'=> 'Bob',
'company'=>'companyName',
'customer_id'=> 123458,
'phone'=> '',
),
4 => array(
'name'=> 'Amy',
'company'=>'companyName',
'customer_id'=> '123456',
'phone'=> '11114',
),
);
$customers = array();
foreach ($data as $value) {
array_push($customers,array_filter( $value));
}
print_r($customers);
return $customers;
The above example will output:
Array
(
[0] => Array
(
[company] => companyName
[customer_id] => 123456
[phone] => 11111
)
[1] => Array
(
[name] => Tom
[customer_id] => 123457
[phone] => 11112
)
[2] => Array
(
[name] => Daniel
[company] => companyName
[phone] => 11113
)
[3] => Array
(
[name] => Bob
[company] => companyName
[customer_id] => 123458
)
[4] => Array
(
[name] => Amy
[company] => companyName
[customer_id] => 123456
[phone] => 11114
)
)
Upvotes: 1
Reputation: 455
On the customers model you could put the logic in there so example;
public function hasMobile() {
if($this->mobile){
return '<p>Mobile: ' . $this->mobile . '</p>';
}
return null;
}
Do that for each item you want to show/not show then in your view you can reference that each time rather than having the if statement all over the place in x amount of views. It would also be good if you needed to update it, update one they would all change
View would be like;
{{ $customer->hasMobile() }}
There is most likely a better way but this is the option I would go for.
Upvotes: 0