dimanche 27 novembre 2016

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></td>
                            @if(!empty($data->name))
                                @if($data->id > 1)
                                    <td></td>
                                @else
                                    <td></td>
                                @endif
                            @else
                                <td>-</td>
                            @endif

                            @if($data->hasartikel->count() > 0)
                                <td><a class="btn btn-default" disabled></a></td>
                            @else
                                <td><a href="#" class="btn btn-default" disabled></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.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gx8LOA
via IFTTT

Aucun commentaire:

Enregistrer un commentaire