I use Auth in all my models to convert datetimes to the user's timezone when retrieved. Now I ran into a situation where the user is not authenticated, and this conversion needs to be done in my model.
My goal would be to retrieve a default timezone from another table like so:
$business = Business::where('id', '=', $id)->first(); // default timezone is in here: $business->timezone
Since I use \Auth::user()->timezone in all my model, is there a place where I should add the code above (I'll need to pass $id which is not available when user is authenticated) for the retrieval of the default timezone, so I can access $business->timezone globally, only when a user is not authenticated?
This is the code I currently have in one of my models.
/**
* Set event_start attribute.
*/
public function setEventStartAttribute($event_start)
{
$this->attributes['event_start'] = Carbon::createFromFormat('Y-m-d H:i', $event_start, \Auth::user()->timezone)->setTimezone('UTC');
}
/**
* Set event_end attribute.
*/
public function setEventEndAttribute($event_end)
{
$this->attributes['event_end'] = Carbon::createFromFormat('Y-m-d H:i', $event_end, \Auth::user()->timezone)->setTimezone('UTC');
}
/**
* Get event_end attribute.
*/
public function getEventEndAttribute($value)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, 'UTC')->setTimezone( \Auth::user()->timezone);
}
/**
* Get event_end attribute.
*/
public function getEventEndAttribute($value)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, 'UTC')->setTimezone( \Auth::user()->timezone);
}
I guess my code would then be changed to something like:
/**
* Set event_start attribute.
*/
public function setEventStartAttribute($event_start)
{
if (Auth::check()) {
$this->attributes['event_start'] = Carbon::createFromFormat('Y-m-d H:i', $event_start, \Auth::user()->timezone)->setTimezone('UTC');
}
else {
$this->attributes['event_start'] = Carbon::createFromFormat('Y-m-d H:i', $event_start, $business->timezone)->setTimezone('UTC');
}
}
Thanks