我正在建立一个时间跟踪器,以便用户可以登记入住和退房。
因此,有两个按钮,我想使用Blade模板引擎一次只显示一个按钮。此按钮将插入到工作日开始和结束的数据库日期时间。
它不是登录状态。用户可以开始工作日,注销或其他任何内容,然后只看到签出按钮,因为用户已签入。
@if ( //checked in )
// button
@endif
我觉得应该有一个变量来设置,然后检查它的状态并显示一个按钮。
题:
如何正确存储用户的状态?将其存储在数据库中?或者我还应该使用什么?
创建一个表:
user_status_in (id, user_id, date, time,status)
确保user_id,date,status具有唯一索引(因此DB不会让用户在同一天签入或签出两次。
您的用户模型:
public function checkIn() {
return $this->hasMany(UserCheckIn::class,"user_check_in");
}
public function checkedInToday() { //True if checked in today
return $this->checkIn()
->where("date","=",date_format(date_create(), "Y-m-d")) //today
->where("status","=",1)
->count() > 0;
}
UserCheckIn.php
class UserCheckIn extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
在您的视图中,您可以执行以下操作:
@if (auth()->user()->checkedInToday())
//Check out button
@else
//Check in button
@endif
您可以通过执行以下操作来检查用户:
$c = new UserCheckIn();
$c->user_id = auth()->user()->id;
$c->date = date_format(date_create(), "Y-m-d"));
$c->time = date_format(date_create(), "H-i-s"));
$c->status = 1;
$c->save();
或者状态为0以结账。
通过这种方式,您还可以保留签到/退出的历史记录
最简单的方法是将状态存储在users
表中。创建一个名为boolean
的status
type列。
然后,要检查当前用户的状态,您将能够使用auth()
全局帮助器:
@if (auth()->check() && auth()->user()->status)
// button
@endif
或Auth
门面:
@if (Auth::check() && Auth::user()->status)
// button
@endif
Laravel> 5.3
@if (Auth::check())
You are signed in.
@else
You are not signed in.
@endif
要么
@unless (Auth::check())
You are not signed in.
@endunless
要么
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest