すべてのモデルでAuthを使用して、検索時に日付時刻をユーザーのタイムゾーンに変換します。今、私はユーザーが認証されていない状況に遭遇し、この変換は私のモデルで行う必要があります。Laravel 5でグローバル関数を作成する正しい方法は何ですか
私の目標は、そうのような別のテーブルからデフォルトのタイムゾーンを取得するために、次のようになります。
$business = Business::where('id', '=', $id)->first(); // default timezone is in here: $business->timezone
私は、\認証を使用するので::ユーザー() - すべての私のモデルで>タイムゾーン、私の場所があります上記のコードを追加する必要があります(ユーザーが認証されていない場合は$ idを渡す必要があります)ので、ユーザーが認証されていない場合にのみ、グローバルに$ business-> timezoneにアクセスできます。
これは私のモデルの1つに現在あるコードです。
/**
* 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);
}
私は私のコードは、その後のようなものに変更されるだろうと思います。
この場合/**
* 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');
}
}
おかげ
ありがとうカスタムヘルパーではありませんか?申し訳ありません、ただ理解しようとしています。 – user3489502
'MyTimezone'はヘルパーとして機能します。あなたは 'MyTimezoneHelper'を呼び出すことができます。ポイントは、DB上で複数のクエリを避けるために 'business-> timezone'情報をキャッシュすることです。気にしない場合は、キャッシュ部分を削除してください。 –
だから、わかっていれば、ヘルパー関数が実行されます(データベースに常に照会します)が、キャッシュは1回実行されます(データベースへの1回の呼び出し)。そのクラスを作成するための最良の場所はどこですか? – user3489502