2017-02-13 53 views
2

我正在构建时间跟踪器,以便用户可以签入和签出。Laravel - 根据用户状态显示和隐藏元素

所以有两个按钮,我想一次只显示一个使用刀片模板引擎。 这个按钮插入数据库日期时间的开始和结束的工作日。

这不是登录状态。用户可以开始工作了一天,注销或什么的,然后看到的只是检查出按钮,因为用户在检查。

@if (//checked in) 
    // button 
@endif 

我觉得应该有一个设置,然后检查它的状态,并显示一个变量按钮。

问题:

如何正确存储用户的状态?将它存储在数据库中?或者我还应该使用什么?

+0

是,将其存储在数据库中。请添加更多信息,这是什么检查/结帐?它是用户的登录状态吗? – Jerodev

回答

1

创建一个表:

user_status_in (id, user_id, date, time,status) 

确保有一个唯一的user_id索引,日期,状态(所以数据库不允许用户在同一天登记或登出两次。

您的用户模型:

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时退出。

这种方式,您也可以保留签入的历史记录/奏

3

最简单的方法是将存储在users表状态。创建一个名为statusboolean类型的列。

然后检查当前用户的身份,你就可以使用auth()全球帮手:

@if (auth()->check() && auth()->user()->status) 
    // button 
@endif 

或者Auth门面:

@if (Auth::check() && Auth::user()->status) 
    // button 
@endif 
0

随着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