I have implemented a table called schedules, it has a field called day.
day is tinyInteger datatype and represents a day of week like Saturday or Wednesday.
As of getting query and presenting to the view how do I convert tinyInt to a representational String?
Also I'm concerned about MVC architecture as representing a day's string is related to the view and not model itself, so what's your opinion about creating a helper class and converting integer to string there?
2 Answers
I would do it in an accessor:
http://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators
So perhaps something like this in your Schedules model:
public function getDayAttribute($day)
{
// Assuming your integer value is between 0 and 6
if($day >= 0 && $day <= 6) {
return jddayofweek($day, 1);
}
return null;
}
Note this assumes your integer is between 0 and 6, and 0 is a Monday.
See jddayofweek for details.
So now when you call $schedule->day you will get a string like Monday.
Alternatively, if you don't want to override the day attribute entirely like this, you can add a pseudo attribute to your model:
protected $appends = ['day_name'];
public function getDayNameAttribute()
{
// Assuming your integer value is between 0 and 6
if($this->day >= 0 && $this->day <= 6) {
return jddayofweek($this->day, 1);
}
return null;
}
Now you can use $schedule->day to get the integer value, or $schedule->day_name to get the string.
5 Comments
day as it is, and have a helper class that one of it's methods map's day integer to a string?I would recommend looking into this library: https://packagist.org/packages/nesbot/carbon It has more than 7 million installs through composer.
Basically, it will provide you with a ton of translation utilities that are generally not provided by the DateTime built in class.
The Laravel way is to inject a repository into the controller wherever you need to "interpret" your model's data. https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/