Laravel - 根据用户状态显示和隐藏元素

时间:2017-02-13 13:32:01

标签: php laravel

我正在构建一个时间跟踪器,以便用户可以办理登机手续和结账。

因此,有两个按钮,我想使用Blade模板引擎一次只显示一个按钮。 此按钮将插入到工作日开始和结束的数据库日期时间。

它不是登录状态。用户可以开始工作日,注销或其他任何内容,然后只查看结帐按钮,因为用户已签入。

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

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

问题:

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

3 个答案:

答案 0 :(得分:3)

最简单的方法是将状态存储在users表中。创建一个名为boolean的{​​{1}}类型的列。

然后,要检查当前用户的状态,您将能够使用status全球帮助者:

auth()

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

Auth

答案 1 :(得分:1)

创建一个表格:

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

确保user_id,date,status的唯一索引(因此数据库不允许用户在同一天签入或签出两次。

您的用户模型:

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结帐。

通过这种方式,您还可以保留签到/退出的历史记录

答案 2 :(得分:1)

使用Laravel&gt; 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
相关问题