Reputation: 1147
I kinda feel weird about the way I fetch models on Eloquent. I would like to know if there's any way I can make my current code look better? Here is it:
Yes I can loop to get less codes but the way I fetch models is my main concern, I mean is there anyway I can reduce the calls to 1 instead of 12?
Thanks!
Upvotes: 0
Views: 95
Reputation: 7371
@Qazi to make the foreach shorter and less if statements lets do some refactoring
$months_keys = ['jan','feb','mar',....];
$months = []
foreach($result as $month){
$key = $months_keys[(int)$month - 1];
$months[$key] = $month;
}
Upvotes: 1
Reputation: 5135
Ok, you can do this Info::get(['encoded']);
you will get the array of encoded field, loop through and make it according to your requirements.
More specific follow this.
Edited
$result =Info::whereMonth('encoded','>=','01')->whereMonth('encoded','<=','12')->get()->first();
here ->first();
will remove the array into array structure. will return [.....]
instead [0=>[....] ]
so loop your result
$months = [];
foreach($result as $month){
if($month == '01'){
$months['jan'] = $month;
}
if($month == '02'){
$months['feb'] = $month;
}
if($month == '03'){
$months['mar'] = $month;
}
//and so on
}
Upvotes: 1