美文网首页
laravel详解

laravel详解

作者: 我是上帝可爱多 | 来源:发表于2017-08-16 18:01 被阅读78次

我好惶恐,今天我又开了个新的专题,那就是世界上最好的语言php,话不多说,我们今天来学习laravel框架的blade模版用法。

1 后台定位视图,传递变量

public function index()
    {
        $title = '文章标题1';
        return view('articles.lists')->with('title',$title);
    }

这是某个controller下面的方法,定位到articles目录下面的lists模版,携带title。

// two way to show
<body>
<h1><?php echo $title; ?></h1>
</body>

<body>
<h1>{{ $title }}</h1>
</body>

当我们想给页面传递一个html代码:

public function index()
    {
        $title = '<span style="color: red">文章</span>标题1';
        return view('articles.lists')->with('title',$title);
    }
<h1>{!! $title !!}</h1>
使用compact传递
public function index()
    {
        $title = '<span style="color: red">文章</span>标题1';
        $intro = '文章一的简介';
        return view('articles.lists',compact('title','intro'));
    }

我们再来看一下模版的使用,这个才是重点。

 <div>{{date('Y-m-d', strtotime($oActivity->start_time))}} <span class="color-red">00:00</span> 至 {{date('Y-m-d', strtotime($oActivity->end_time))}} <span class="color-red">23:59</span></div>

strtotime是把时间字符串转为时间戳,这是一个在模版里用函数的栗子。

看一个条件判断:

<div class="fr">
         <a href="{{$oActivityList->activity_url}}" class="activity-btn yellow-btn @if($oActivityList->status == 1)green-btn@endif @if($oActivityList->status == 2)start@endif @if($oActivityList->status == 3)gray-btn@endif">
               @if($oActivityList->status == 1)
                        未开始
               @elseif($oActivityList->status == 2)
                        进行中
               @else
                        已结束
               @endif
                            </a>
                        </div>

我们可以看到居然能在class里面判断写类名。

如何写循环渲染页面:

@foreach($items as $item)
                    <div class="unit">获得<span>{{$item['reward']}}}</span>元返现奖励</div>
                    <div class="unit">您已累计充值<span>{{$charge}}/{{$item['amount']}}}</span>元</div>
                    <div class="unit">
                        @if($item->status == 'reach')
                            <button class="reach" data-toggle="modal" data-target="#get-btn"></button>
                        @elseif($item->status == 'finish')
                            <button class="finish"></button>
                        @else
                            <button class="unreach"></button>
                        @endif
                    </div>
 @endforeach

当你在使用@foreach的时候,可以结束循环或继续。

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

当然你也可以换一种方式

@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

这样看起来是不是更简洁。。。

下面来一个复杂的栗子:

<tbody>
        <?php $fTotalAmount = $fTotalPrize = $fTotalCommission = 0; ?>
        @if (count($datas))
            @foreach ($datas as $data)
            <tr>
                <td> {{$data->username }} </td>
                <td> {{ $aLotteries[$data->lottery_id] }} </td>
                <td>
                    <a class="view-detail" href="{{route('projects.view', $data->id)}}">{{ $data->serial_number_short }}</a><textarea class="data-textarea" style="display:none;">{{ $data->serial_number }} </textarea>
                </td>
                <td> {{ $data->issue }} </td>
                <td> {{ $data->title }} </td>
                <td>
                    @if ( strlen( $data->display_bet_number) > 5 )
                        <a class="view-detail" href="{{route('projects.view', $data->id)}}" target="_blank">详细号码</a><textarea class="data-textarea" style="display:none;">{{ $data->display_bet_number }} </textarea>
                    @else
                        {{ $data->display_bet_number }}
                    @endif
                </td>
                <td> {{ $data->amount_formatted }} </td>
                <td> {{ $data->prize_formatted ? $data->prize_formatted : 0.00}} @if($data->is_overprize) (奖金超限) @endif </td>
                <td>{{ $data->prize_group_real.'-'.$data->commission_formatted.'%' }} </td>
                <td> {{ $data->formatted_status }} </td>
            </tr>
            <?php if($data->status != Project::STATUS_DROPED){$fTotalAmount += $data->amount;$fTotalPrize += $data->prize; $fTotalCommission += $data->commission;} ?>
            @endforeach
        @else
            <tr><td colspan="12">没有符合条件的记录,请更改查询条件</td></tr>
        @endif
    </tbody>

我们可以看到这一段:

// 同时生明3个变量 都为0
<?php $fTotalAmount = $fTotalPrize = $fTotalCommission = 0; ?>

在每次渲染完一个tr的时候,有这一段:

<?php if($data->status != Project::STATUS_DROPED){$fTotalAmount += $data->amount;$fTotalPrize += $data->prize; $fTotalCommission += $data->commission;} ?>

实际上是每次判断后做累加,而这个变量时做出了改变。

<tfoot>
        @if (isset($bHasSumRow) && $bHasSumRow)
        <tr>
            <td>本页小结</td>
            <td> {{ number_format($fTotalAmount, 2) }}</td>
            <td>{{ number_format($fTotalPrize,2)}}</td>
            <td> &nbsp;</td>
            <td> &nbsp;</td>
        </tr>
        @endif
    </tfoot>

在tr渲染完后,可以在tfoot那里拿到修改完的值。

用过jade模版的人都知道,我们在js中无法直接操作后台给的数据,而blade可以。

var global_game_config_ssc = {{ $sLotteryConfig }};

我们已经讲了后台怎么控制跳到什么页面,传递变量给前台,那么还有个问题,如何到达指定的controller从而去到指定的页面。。。

<ul>
     @foreach ($aLotteries as $key => $aLottery)
         <li class="{{ $iLotteryId == $aLottery['id'] ? 'current' : '' }}"><a href="{{ route('user-trends.trend-view', [$aLottery['id']]) }}">{{ $aLottery['name'] }}</a></li>
     @endforeach
</ul>

我们这里看到了每个li里面都有一个跳转,其实就是路由,控制页面的去向。

<?php
routes/trend
Route::group(['prefix' => 'user-trends'],function (){
    $resource   = 'user-trends';
    $controller = 'UserTrendController@';
    Route::get('trend-view/{lottery_id?}/{num_type?}', ['as' => $resource . '.trend-view',  'uses' => $controller . 'trendView']);
    Route::match(['GET', 'POST'],        'trend-data', ['as' => $resource . '.trend-data',  'uses' => $controller . 'getTrendData']); //->before('ajax');

});

当我们点击a标签,他会走下面这个:

Route::get('trend-view/{lottery_id?}/{num_type?}', ['as' => $resource . '.trend-view',  'uses' => $controller . 'trendView']);

注意lottery_id和num_type其实都可以不传的。点击后会进入UserTrendController的trendView方法。
那我们来看下这个controller方法是怎么写的

public function trendView ($iLotteryId = null, $sTrendType = null)
    {
        // 没有彩种参数, 则取彩种表的第一个彩种
        if ($iLotteryId) {
            $oLottery = Lottery::find($iLotteryId);
        } else {
            $oLottery = Lottery::first();
            $iLotteryId = $oLottery->id;
        }
        if (empty($oLottery)){
            $this->halt(false,'lottery-missing',Lottery::ERRNO_LOTTERY_MISSING);
        }

        $oSeries  = Series::find($oLottery->series_id);
        $sSeriesName  = strtolower($oSeries->name);
        $sLotteryName = $oLottery->friendly_name;
        $aViewTypes  = [];
        $aEnabledViewTypes = Config::get('trend.' . $oLottery->series_id);
        foreach ($aEnabledViewTypes as $sViewType) {
            $aViewTypes[$sViewType] = static::$aViewTypes[$sViewType];
        }

        // 没有走势图类型, 则取配置数组的第一个
        $sTrendType or $sTrendType = $aEnabledViewTypes[0];
        $sTrendTypeEnName = $aViewTypes[$sTrendType];
        if($oSeries->id==21){
            $this->view     = $this->customViewPath . '.lhc.' . $sTrendTypeEnName;
        }else{
            $this->view     = $this->customViewPath . '.' . $sSeriesName . '.' . $sTrendTypeEnName;
        }

        $sTrendTypeName = __('_trend.' . ($sTrendTypeEnName));
        // pr($sTrendTypeName);exit;
        $aConfigs       = & $this->_getTrendConfig($iLotteryId, $sTrendType);
        $sConfigs       = json_encode($aConfigs);
        $this->setVars(compact('sConfigs', 'oSeries', 'iLotteryId', 'sTrendType', 'sLotteryName', 'aViewTypes', 'sTrendTypeName'));
        return $this->render();
    }

当我们访问 '域名/user-trends/16' 时,会走这个方法。

我们讲了路由,控制去向,还能获取参数,然后模版,变量传递,还差什么呢?就是数据持久层model了,我们来看一个model

<?php

/**
 * Class Activitys - 七夕活动表
 *
 */
class ActivityQixi extends BaseModel {

    protected $table = 'activity_qixi';
    public $orderColumns = [ 'id' => 'desc'];

    protected $fillable = [
        'user_id',
        'type',
        'created_at',
        'updated_at',
    ];
    public static $resourceName = 'ActivityQixi';
    
    public static $columnForList = [
        'user_id',
        'type',
        'created_at',
        'updated_at',
    ];
    public static $titleColumn = 'id';
    public static $rules = [
        'user_id' => 'required',
        'type' => 'required',
    ];
    
    /*
     * 添加记录
     */
    public static function add($user_id,$type) {
        $data = new ActivityQixi();
        $data->user_id = $user_id;
        $data->type = $type ;
        $data->save();
    }
}

这个实体类就对应一个数据库表,表有四个字段,$columnForList数组标出来了,$rules规定了字段规则,add方法是往数据库新增1条记录。

 ActivityQixi::add(Session::get('user_id'), $type);   //增加领奖记录 

在controller里面调用就是如此简单。

我们来看一个比较符合正常的rule

public static $rules = [
        'user_id' => 'required|integer',
        'cellphone_number' => [
            'required',
            'regex:/^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])[0-9]{8}$/'
        ],
        'post_code' => 'regex:/^[0-9]{6}$/',
        'true_name' => 'required|min:2|max:10',
        'address' => 'required|between:5,100',
        'email' => 'email'
    ];

/**
     * 写入用户数据
     */
    public static function insertUserInfo(array $data)
    {
        if (! is_array($data)) {
            return false;
        }
        $aInserData = [];
        foreach ($data as $key => $value) {
            if ($key == 'true_name' || $key == 'email' || $key == 'cellphone_number' || $key == 'address' || $key == 'post_code') {
                $value = Encrypt::encode($value);
            }
            $aInserData[$key] = $value;
        }
        return self::insert($aInserData);
    }

好了吧,下班了,今天就到这。。。

相关文章

  • 浅谈多个社交账号的绑定设计

    Dearmadman 在 Laravel Socialite 详解 中使用 larastarscn/sociali...

  • Laravel 5.2 新特性系列 —— 多用户认证功能实现详解

    Laravel 5.2 新特性系列 —— 多用户认证功能实现详解 Laravel 5.2新增多用户认证支持,即同时...

  • Laravel 添加 jwt-auth

    JWT 完整使用详解(中文) https://laravel-china.org/articles/10885/f...

  • laravel详解

    我好惶恐,今天我又开了个新的专题,那就是世界上最好的语言php,话不多说,我们今天来学习laravel框架的bla...

  • Laravel队列详解

    1.队列的应用场景: PHP在异步编程上的短板是众所周知的,这也是当年PHP能够迅速火起来的一个重要特性,当然,这...

  • Laravel Socialite 详解

    不久之前 Dearmadman 曾写过一篇 使用 Laravel Socialite 集成微信登录 的文章,但是似...

  • laravel事件详解

    事件的作用:业务解耦,比如注册成功后发邮件,短信,赠送优惠券,可以拆分代码,一个事件可以对应多个监听器,如果注册成...

  • laravel自定义分页

    Paginate分页 手动分页详解 laravel自带的分页功能十分强大,只不过,在使用 groupBy 语句的分...

  • 资料链接地址备忘录

    资料链接地址备忘录 Artisan 命令行接口 Laravel 5.2 新特性系列 —— 多用户认证功能实现详解 ...

  • laravel之队列详解

    说明 laravel5.2,redis3 配置 就是把队列文件改成redis驱动config/queue.php....

网友评论

      本文标题:laravel详解

      本文链接:https://www.haomeiwen.com/subject/busirxtx.html