我用Laravel-一些小技巧

1.控制器的靈活性(支持Ajax)

控制器要支持普通請(qǐng)求和AJAX請(qǐng)求,體現(xiàn)在參數(shù)的獲取以及結(jié)果返回。
比如:

public function update(Request $request, $model_id = 0)
    {
        try {
// 參數(shù)獲取
            if (!$model_id) {
                $model_id      =  $request->get("model_id");
                if (!$model_id) {
                    throw new \Exception("Invalid input", "4007");
                }
            }
//邏輯處理

//結(jié)果返回
            if ($request->ajax()) {
                return Response::json([
                    "errcode"     =>  "0000",
                    "errmsg"      =>  "Success"
                ]);
            } else {
                return redirect() -> to('/admin/user/wxtmpl/show'."/".$model->id) -> with("message", "更新消息成功");
            }
        } catch (\Exception $e) {
            info(__METHOD__."\n".$e->getTraceAsString());
            info($e->getCode()." | ".$e->getMessage());
            if ($request->ajax()) {
                return Response::json([
                    "errcode"   =>  $e->getCode()? $e->getCode(): "5000",
                    "errmsg"    =>  $e->getMessage(),
                ], JSON_UNESCAPED_UNICODE);
            } else {
                return redirect()->back()->withInput()->withErrors([
                    "fail"      =>  $e->getMessage(),
                ]);
            }
        }
    }

2.參數(shù)的合法性驗(yàn)證

在Laravel里面,提供了Validator門面來(lái)進(jìn)行參數(shù)合法性驗(yàn)證 。

use Illuminate\Support\Facades\Validator;

//基本用法
$validator    =  Validator::make($request->all(), [
                "first"                =>  "required",
            ], [
                "first.required"       =>  "請(qǐng)?zhí)顚?xiě)first",
            ]);
            if ($validator->fails()) {
                $msg = $validator->messages()->first();
                throw new \Exception($msg);
            }

//自定義錯(cuò)誤信息,在本例中,:attribute占位符將會(huì)被驗(yàn)證時(shí)實(shí)際的字段名替換
//你還可以在驗(yàn)證消息中使用其他占位符
            $messages          =  [
                "same"         =>  "The :attribute and :other must match",
                "size"         =>  "The :attribute must be exactly :size"
            ];

3.框架調(diào)用命令行

$exitCode = Artisan::call("shencom:get:tags:list:wx", ["acctid" => $acct_id])
即,使用Artisan門面的call函數(shù)。

4.RequestOnly

$data = $request->only([
    "name", "desc", "logo", "cate_id"
]);

可獲得和下面語(yǔ)句相同的效果

$data = array(
    "name" => $request->get["name"],
    "desc" => $request->get["desc"],
    ....
);

5.Transaction事務(wù)

在查看文章的時(shí)候給文章的瀏覽量增加1。

//控制器中的方法
public function articleDetail($route, $id){
    try{
        \DB::transaction(function() use($id){
            Article::addViewCnt($id);
        });
    }
}

//模型中的方法
use SC\Forum\Models\Article as BaseArticle;
class Article extends BaseArticle{
    public static function addViewCnt( $article_id ){
        $result = Static::find($article_id);
        if($result){
            $result->read)cnt += 1;
            $result->save();
            return true;
        }else{
            return false;
        }
    }
}

6.在Laravel5.1中使用SMTP驅(qū)動(dòng)實(shí)現(xiàn)郵件發(fā)送

參考
在config/mail.php里面做如下配置

return[
    'driver' => 'smtp',
    'host' => 'smtp.qq.com',
    'port' => 465,
    'from' => ['address' => '893302826@qq.com', 'name' => 'LeoStupidWise'],
    'encryption' => 'ssl',
    'username' => '893302826@qq.com',
    'password' => 'lxmixneovtxnbfgf',
    'sendmail' => '/usr/sbin/sendmial -bs',
    'pretend' => false,
]

HOST:郵箱所在主機(jī),163對(duì)應(yīng)smtp.163.com,QQ使用smtp.qq.com,其實(shí)還有更復(fù)雜的情況,QQ郵箱可以在郵箱設(shè)置里面去看到。
PORT:郵箱發(fā)送服務(wù)端口號(hào),默認(rèn)25,如果設(shè)置SMTP的SSL加密,該值為465。嘗試時(shí),25端口沒(méi)有發(fā)送成功,只有設(shè)置SSL在465才能發(fā)送成功。
FROM:address表示發(fā)送郵箱,name表示發(fā)送郵箱使用的用戶名。
ENCRYPTION:加密類型,null表示不加密,也可以設(shè)置為tls/ssl。
USERNAME:表示郵箱賬號(hào)。
PASSWORD:表示登陸郵箱對(duì)應(yīng)的授權(quán)碼,QQ郵箱在設(shè)置中能獲取。
PRETEND:是否將郵件發(fā)送記錄到日志中。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容