Laravel代码片段记录一

393 阅读1分钟

1、控制器中使用权限控制

用到Laravel-permission插件

/**
 * PeopleController constructor.
 *
 * @param PersonRepository $repository
 * @param PersonValidator $validator
 */
public function __construct(PersonRepository $repository, PersonValidator $validator)
{
    $this->middleware(['permission:dagl_all|dagl_readonly']);
    $this->repository = $repository;
    $this->validator  = $validator;
}

2、使用Gate判断权限是否满足给定的数组中的某一个

Gate::any(['dagl_all', 'dagl_readonly']);

3、API中人性化的时间显示

3.1、设置Carbon中文显示

App\Providers\AppServiceProviderboot函数中添加如下代码

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //...
        //设置Carbon中文显示
        Carbon::setLocale('zh');
        //...
    }

    //...
}

3.2、在 Model 中设定要人性化显示的字段。以 Article Modelcreated_at 字段为例

use Carbon\Carbon;

public function getCreatedAtAttribute($date) {
    if (Carbon::now() > Carbon::parse($date)->addDays(15)) {
        return Carbon::parse($date);
    }

    return Carbon::parse($date)->diffForHumans();
}

就可以直接调用了$article->created_at; // 1秒前

4、migrate中的path参数

 php artisan migrate --path="database/migrations/2018_12_31_173608_create_settings_table.php"

5、实现用户无操作停留过久自动退出登录

在写一个 Web 应用的时候,很多人都遇到过这样的需求:如何实现在一个用户登录进来之后,停留时间过久(页面没有操作和活动),我们就自动将用户退出登录?

解决办法其实很简单,我们在 Laravel 中自定义一个 Middleware 就可以实现:

namespace App\Http\Middleware;

use Closure;

class SessionTimeout {

    protected $timeout = 1200;
    public function handle($request, Closure $next)
    {
        $isLoggedIn = $request->path() != 'logout';
        if(! session('lastActivityTime')){
            app('session')->put('lastActivityTime', time());
        } elseif(time() - app('session')->get('lastActivityTime') > $this->timeout){
            app('session')->forget('lastActivityTime');
            $cookie = cookie('intend', $isLoggedIn ? url()->current() : 'home');
            $email = $request->user()->email;
            auth()->logout();
            return route('login')->withInput(['email' => $email])->withCookie($cookie);
        }
        $isLoggedIn ? app('session')->put('lastActivityTime', time()) : app('session')->forget('lastActivityTime');
        return $next($request);
    }

}

我们主要是通过 lastActivityTime 这个记录来判断用户是否有对应的操作(刷新页面或者是访问新的页面等), 如果在 20 分钟内没有操作的话,我们就会跳转到登录页面。

6、SimpleXMLElement 转为 array

开发飞猪订单接口的时候遇到的

$resp       = $c->execute($req, $this->sessionKey);
//转为obj
$obj        = simplexml_load_string($resp->asXML());
$json       = json_encode($obj);
//获得array格式
$respData   = json_decode($json, true);

7、日志记录

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\OperationLog;
use Illuminate\Support\Facades\Log;

class ApiOperationLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $response = $next($request);

        $input = $request->all();

        //状态码
        $statusCode = $response->getStatusCode();

        //请求参数
        $inputJson = json_encode($input, JSON_UNESCAPED_UNICODE);

        //返回内容格式化
        $responseJson = json_encode($response, JSON_UNESCAPED_UNICODE);

        $uid = 0;
        if(Auth::check()) {
            $uid = (int) Auth::id();
        }

        $logLocal['uid'] = $uid;
        $logLocal['path'] = $request->path();
        $logLocal['method'] = $request->method();
        $logLocal['ip'] = $request->ip();
        $logLocal['input'] = $inputJson;
        $logLocal['result'] = $response->original;
        $logLocal['created_at'] = date('Y-m-d H:i:s');
        $logLocal['http_code'] = intval($statusCode);

        switch ($statusCode) {
            // case '200':
            // case '201':
            // case '422':
            // case '401':
            //     Log::info(json_encode($logLocal,JSON_UNESCAPED_UNICODE));
            //     break;
            case '401':
            case '422':
            case '400':
            case '500':
                //记录到数据库
                $logLocal['result'] = json_encode($response->original,JSON_UNESCAPED_UNICODE);
                \DB::connection('mysql_log')->table('operation_log')->insert($logLocal);
                break;   
            default:
                Log::notice('未知的状态码:'.$statusCode);
                break;
        }
 
        return $response;
    }
}

7、分页的同级附加额外的参数返回

8、邮件用多个邮件服务器以及添加抄送

/*
 * multiple mail configurations
 */
$toEmail = $request->get("email");
// backup current mail configs
$backup = Mail::getSwiftMailer();
// Setup your gmail mailer
$transport = new Swift_SmtpTransport(env('MO_MAIL_HOST'), env('MO_MAIL_PORT'), env('MO_MAIL_ENCRYPTION'));
$transport->setUsername(env('MO_MAIL_USERNAME'));
$transport->setPassword(env('MO_MAIL_PASSWORD'));
// Any other mailer configuration stuff needed...
$gmail = new Swift_Mailer($transport);
// Set the mailer as gmail
Mail::setSwiftMailer($gmail);
// Send your message
Mail::to($toEmail)->send((new OrderNotice($data))->subject("產品預訂成功,請盡快與行家假期-長暉國際旅遊有限公司聯絡"));
// Restore your original mailer
Mail::setSwiftMailer($backup);
/*
 *添加抄送 ->cc(array or string arg)
 */
$this->from(env('MO_MAIL_FROM_ADDRESS'), env('MO_MAIL_FROM_NAME'))
    ->cc(env('MO_MAIL_CC_ADDRESS'))
    ->markdown('emails.order.notice_mo_new');