laravel初体验写个简单的抽奖案例

来源:互联网 发布:hub网络 编辑:程序博客网 时间:2024/06/05 17:11

刚来新公司用的是laravel框架,所以练习一下写了个简单的抽奖案例。

首先是登录页面

这里写图片描述

登录后端代码

    public function login(Request $request)    {        if ($request->isMethod('post')) {            $requestInfo = $request->all();            //判断用户名密码是否为空            if (empty($requestInfo['user_name']) || empty($requestInfo['password'])) {                echo '<script>alert("用户名或密码不能为空");</script>';                return view('index/login');            }            //查找是否有对应用户名密码            $userInfo = UserModel::where('user_name',$requestInfo['user_name'])                                 ->select('password','uid')                                 ->first();            if (empty($userInfo)) {                echo '<script>alert("用户名不存在!");</script>';                return view('index/login');            }            //核对密码是否匹配            if (md5($requestInfo['password']) == $userInfo['password']) {                session(['user_name' => $requestInfo['user_name'],                         'uid' => $userInfo['uid']]);                echo '<script>location.href="/index/index"</script>';            }        }        return view('index/login');    }

登录页面前端代码

    <h1>登录页面</h1>    <br>    <form action="/index/login" method="POST">        <input type="hidden" name="_token" value="{{csrf_token()}}">        用户名:<input type="text" name="user_name">        <br>        密码:<input type="password" name="password">        <br>        <input type="submit" value="登录">    </form>

建表语句

    CREATE TABLE `lty_user` (      `uid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,      `user_name` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '用户名',      `password` CHAR(36) NOT NULL DEFAULT '' COMMENT '用户密码',      `created_at` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '创建时间',      `updated_at` INT(11) NOT NULL DEFAULT '0' COMMENT '更新时间',      `chance` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '剩余机会',      PRIMARY KEY (`uid`)    ) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='用户表'

登录后页面,效果有点爆炸 :)

这里写图片描述

后端代码

    public function index(Request $request)    {        $sessionInfo = $request->session()->all();        if (empty($sessionInfo['user_name'])) {            echo '<script>alert("请先登录!");location.href="/index/login"</script>';        }        //查询剩余机会        $chance = UserModel::where('uid',$sessionInfo['uid'])->first();        //查找用户自己的中奖记录        $awardLogInfo = AwardLogModel::where('uid',$sessionInfo['uid'])->get();        //查找十条总共用户中奖记录        $customerLogInfo = AwardLogModel::select('user_name','award_name')                                        ->limit(10)                                        ->orderBy('alid','desc')                                        ->get();        return view('index/index', [            'user_name' => $sessionInfo['user_name'],            'chance' => $chance['chance'],            'self_info' => $awardLogInfo,            'customer_info' => $customerLogInfo        ]);    }

前端代码

    <span>{{$user_name}}的首页</span>    <span><input type="button" value="退出登录" onclick="location.href='/index/logout'"></span>    <h1>抽奖首页</h1>    <h3 id="chance">今日剩余机会:{{$chance}}</h3>    <h3>奖品列表:</h3>    <table style="border:1px solid black">        <tr>            <td>1W银子</td>            <td>2K银子</td>            <td>500银子</td>            <td>50银子</td>        </tr>    </table>    <br>    <input type="button" value="开始抽奖" onclick="startLottery();">    <br>    <h3>中奖记录:</h3>    @foreach($self_info as $sfk=>$sfv)    <span>{{$sfv->award_name}}</span>    @endforeach    <br>    <h3>最近玩家中奖记录:</h3>    @foreach($customer_info as $cusk=>$cusv)    <span>{{$cusv->user_name}}</span>    <span>{{$cusv->award_name}}</span>    <br>    @endforeach

奖品表结构

    CREATE TABLE `lty_award` (      `awid` TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '奖品id',      `award_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '奖品名称',      `award_attr` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '奖品属性特征',      `award_num` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '奖品数量',      `award_rate` FLOAT UNSIGNED NOT NULL DEFAULT '0' COMMENT '奖品比率',      `created_at` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '创建时间',      `updated_at` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '更新时间',      PRIMARY KEY (`awid`)    ) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='奖品信息表'

抽奖算法

    public function start(Request $request)    {        $sessionInfo = $request->session()->all();        //判断今日次数是否足够,不够则无法抽奖        $chance = UserModel::where('uid',$sessionInfo['uid'])                            ->select('chance')                            ->first();        if ($chance['chance'] == 0) {            return '今日抽奖次数已用完';        }        //更新剩余次数        UserModel::where('uid',$sessionInfo['uid'])                 ->update(['chance' => $chance['chance']-1]);        $num = rand(1,1000);        $one = 1000 * (0.002);        $two = 1000 * (0.01);        $three = 1000 * (0.04);        $four = 1000 * (0.4);        $award = new AwardModel();        $awardLog = new AwardLogModel();        if ($num >= 1 && $num <= $one) { // 落在一等奖的范围内            //查找中奖信息表看是否已经中过该奖品,如果中了就不再发奖            $awardLogInfo = $awardLog->where('awid',1)                                     ->where('uid',$sessionInfo['uid'])                                     ->first();            if (!empty($awardLogInfo)) {                return '你已经中了1W银子';            }            //查看库存,如果已经抽完则返回如下            $upInfo = $award->updateAwardNum(1);            if (!$upInfo) {                return '1W银子已被抽完';            }            $awardLog->saveAwardLog($sessionInfo['uid'],$sessionInfo['user_name'],1);            return  '恭喜你中了1W银子';        } else if ($num >= ($one + 1) && $num <= ($one + $two)) { // 落在二等奖的范围内            //查找中奖信息表看是否已经中过该奖品,如果中了就不再发奖            $awardLogInfo = $awardLog->where('awid',2)                                     ->where('uid',$sessionInfo['uid'])                                     ->first();            if (!empty($awardLogInfo)) {                return '你已经中了2K银子';            }            //查看库存,如果已经抽完则返回如下            $upInfo = $award->updateAwardNum(2);            if (!$upInfo) {                return '2K银子已被抽完';            }            $awardLog->saveAwardLog($sessionInfo['uid'],$sessionInfo['user_name'],2);            return  '恭喜你中了2K银子';        } else if ($num >= ($one + $two + 1) && $num <= ($one + $two + $three)) { // 落在三等奖的范围内            //查找中奖信息表看是否已经中过该奖品,如果中了就不再发奖            $awardLogInfo = $awardLog->where('awid',3)                                     ->where('uid',$sessionInfo['uid'])                                     ->first();            if (!empty($awardLogInfo)) {                return '你已经中了500银子';            }            //查看库存,如果已经抽完则返回如下            $upInfo = $award->updateAwardNum(3);            if (!$upInfo) {                return '500银子已被抽完';            }            $awardLog->saveAwardLog($sessionInfo['uid'],$sessionInfo['user_name'],3);            return  '恭喜你中了500银子';        } else if ($num >= ($one + $two + $three +1) && $num <= ($one + $two + $three + $four)) { // 落在四等奖的范围内            //查找中奖信息表看是否已经中过该奖品,如果中了就不再发奖            $awardLogInfo = $awardLog->where('awid',4)                                     ->where('uid',$sessionInfo['uid'])                                     ->first();            if (!empty($awardLogInfo)) {                return '你已经中了50银子';            }            //查看库存,如果已经抽完则返回如下            $upInfo = $award->updateAwardNum(4);            if (!$upInfo) {                return '50银子已被抽完';            }            $awardLog->saveAwardLog($sessionInfo['uid'],$sessionInfo['user_name'],4);            return  '恭喜你中了50银子';        } else {            return '谢谢惠顾!';        }    }

前端ajax请求

    function startLottery(){            $.ajax({                type:'POST',                url:'/index/start',                dataType:'text',                headers:{                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')                },                success:function(data){                    console.log(data);                    alert(data);                    location.reload();                }            });        }

中奖记录表结构

    CREATE TABLE `lty_award_log` (      `alid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,      `uid` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '用户uid',      `user_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '中奖人',      `awid` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0' COMMENT '奖品id',      `award_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '奖品名称',      `created_at` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '中奖时间',      `updated_at` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '更新时间',      PRIMARY KEY (`alid`)    ) ENGINE=INNODB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT='用户对应中奖记录'

相关类方法

更新奖品库存

    public function updateAwardNum($id)    {        //先查询库存是否为0了        $awardInfo = $this->where('awid',$id)                          ->select('award_name','award_num')                          ->first()                          ->toArray();        if ($awardInfo['award_num'] == 0) {            return false;        }        // 利用事务机制来更新库存        DB::beginTransaction();        try {            $this::where('awid',$id)->update(['award_num' => $awardInfo['award_num'] - 1]);            //提交事务            DB::commit();        } catch (Exception $e) {            //回滚            DB::rollBack();        }        return $awardInfo;    }

记录中奖信息

    public function saveAwardLog($uid,$userName,$id)    {        //获得奖品信息        $awardInfo = AwardModel::where('awid',$id)->first()->toArray();        //保存至中奖记录表        $input = [            'uid' => $uid,            'user_name' => $userName,            'awid' => $id,            'award_name' => $awardInfo['award_name']        ];        $this::create($input);    }