学堂 学堂 学堂公众号手机端

laravel小技巧

lewis 1年前 (2024-03-07) 阅读数 3 #技术


1、自增字段不修改updated_at

$mE= Merchant::where('user_id',$id)->first();
$mE->timestamps = false;
$mE->increment('read_count');


2、全局函数

在composer.json里面加入files

"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Common/common.php"
]
},

执行 composer dump-auto

3、301重定向

header("Location: http://www.baidu.com",TRUE,301);exit;

也可以

header(‘HTTP/1.1 301 Moved Permanently‘);
header(‘Location: http://www.baidu.com‘);
exit;

4、abc.com跳转到www.abc.com

if($_SERVER['HTTP_HOST'] == 'abc.com'){
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.'https://www.abc.com/'.ltrim(\Request::path(),'/'));
exit;

}

5、配置伪静态

1、可以通过rewrite

2、通过laravel 301路由实现

Route::get('{prefix}/{id}',function(){

header('HTTP/1.1 301 Moved Permanently');
header('Location: '.'http://www.abc.com/'.ltrim(Request::path().'.html','/'));
exit;

})->where(['id'=>'(\d+)']);

可以匹配到 article/1 /post/1 answer/1 等,匹配后article/1.html /post/1.html answer/1.html

6、使用递归获取父数组

$parentArray = Category::all()->pluck('parent_id','id');

$result = [];

getParentArray(20, $result, $parentArray);

function getParentArray($id, $res, $pA){

if(isset($pA[$id])) {
$res[] = $pA[$id];
return getParentArray($pA[$id], $result, $pA);
}
return $res;
}

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门