Laurensius Tony Laurensius Tony - 6 days ago 7
PHP Question

validation for laravel object variable that empty or not exist

i trying to figure out the best way or simplest way to handle laravel object variable that is empty or not exist...

for now i tried to do this i have come up with 2 solution but both of them are feel not a simplest or cleanest way.

first way is in controller after getting laravel object, i do foreach loop and in there i do checking if there is empty or not exist variable, if yes then replace it with '-'.

so in my controller it will be

$dataarticle = Article::with('categories')
->get();
$i = 0;
foreach($dataarticle as $data){
$datas[$i] = array(
'id' => !empty($data->id) ? $data->id : '-',
'name' => !empty($data->name) ? $data->name : '-',
'category' => !empty($data->categories->name) ? $data->categories->name : '-',
'created_at' => !empty($data->created_at) ? $data->created_at : '-',
);
$i++;
}


and in my view i just do another foreach loop in my table.... it looks good but it also mean i need to do 2 times foreach.

the other approach is do a variable check in view so i just need to do foreach loop once... but it will make my view code to be messy.. like this

@foreach($datas2 as $data)
<tr>
<td class="bg-aqua disabled color-palette"></td>
<td hidden>{{ $data->id }}</td>
@if(!empty($data->name))
@if($data->id > 1)
<td>{{ $data->name }}</td>
@else
<td>{{ $data->name }}</td>
@endif
@else
<td>-</td>
@endif

@if($data->hasartikel->count() > 0)
<td><a class="btn btn-default" disabled>{{ $data->jumlah }}</a></td>
@else
<td><a href="#" class="btn btn-default" disabled>{{ $data->hasartikel->count() }}</a> </td>
@endif
</tr>
@endforeach


so maybe there is a function or method or command to do it in much more simpler way? since it will be very tiring if you have a lot of variable in your table and keep to do pretty much the same thing for each variable.

Answer

Just add getFieldAttribute in your model for each field, so it can be used anywhere by just one time config

class Article extends Model
{
    public function getNameAttribute($value)
    {
        return !empty($value) ? $value : '-';
    }
}

So , in view can simply call the variable as below. No need to reformat

<td>{{ $data->name }}</td>

Check details here

Comments