Initial commit

main
liutk 2024-06-06 10:08:04 +08:00
commit 21a291f1a6
608 changed files with 35309 additions and 0 deletions

18
.editorconfig 100644
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

59
.env.example 100644
View File

@ -0,0 +1,59 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=public
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored 100644
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

19
.gitignore vendored 100644
View File

@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

5
README.md 100644
View File

@ -0,0 +1,5 @@
composer install
php artisan g:k
php artisan storage:link
php artisan admin:install
php artisan db:seed

View File

@ -0,0 +1,281 @@
<?php
namespace App\Admin;
use App\Models\Keyword;
use Slowlyo\OwlAdmin\Renderers\BaseRenderer;
use Slowlyo\OwlAdmin\Renderers\WangEditor;
class Components extends BaseRenderer {
/**
* 父级选择器
*/
public function parentControl($apiUrl = null, $name ='parent_id', $label = null, $labelField = 'name', $valueField = 'id')
{
return amisMake()->TreeSelectControl()->source($apiUrl)
->name($name)->label($label ?? __('admin.components.parent_select'))
->showIcon(false)
->labelField($labelField)
->valueField($valueField);
}
/**
* 排序字段
*/
public function sortControl($name ='sort', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.order'))
->displayMode('enhance')
->value(0)
->min(0);
}
/**
* 2位小数输入框
*/
public function decimalControl($name ='decimal', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.decimal'))
->kilobitSeparator(true)
->percision(2)
->step(0.01)
->value(0.00)
->min(0);
}
/**
* 富文本编辑器
*/
public function fuEditorControl($name ='content', $label = null, $height = 530)
{
return WangEditor::make()
->name($name)->label($label ?? __('admin.components.content'))
->height($height)
->excludeKeys(['group-video']);
}
/**
* 开关
*/
public function enableControl($name = 'is_enable', $label= null, $mode = 'horizontal'){
return amisMake()->SwitchControl()
->name($name)->label($label ?? __('admin.components.status'))
->mode($mode)
->onText(__('admin.components.status_map.enabled'))->offText(__('admin.components.status_map.disabled'));
}
/**
* 图片上传
*/
public function imageControl($name, $label){
return amis()->ImageControl($name, $label)
->joinValues(false)
->autoUpload(true)->maxSize('5*1024*1024');//不能大于5M
}
/**
* 图片上传,带裁剪
*/
public function cropImageControl($name, $label, $aspectRatio = null){
$cropImage = amis()->ImageControl($name, $label)->joinValues(false);
// if($aspectRatio){
$cropImage->crop([
'aspectRatio' => $aspectRatio ?? 1
]);
// }
$cropImage->autoUpload(true);
return $cropImage;
}
/**
* 普通文件上传
*/
public function fileControl($name, $label, $accept = '.txt', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(false)
->maxSize(20*1024*1024)
->accept($accept);
}
public function chunkFileControl($name, $label, $accept = '*', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(true)
->accept($accept)
->startChunkApi(admin_url('start_chunk_upload_file'))
->chunkApi(admin_url('save_chunk_upload_file'))
->finishChunkApi(admin_url('finish_chunk_upload_file'));
}
/**
* 标签选择
*/
public function keywordsTagControl($name = 'tags', $label= null, $pKey = null){
return amisMake()->TagControl()
->name($name)->label($label ?? __('admin.components.tag'))
->maxTagLength(0)
->options(Keyword::where('parent_key', $pKey)->pluck('name', 'id')->toArray());
}
public function keywordsTag($label = null, $color = null){
if($color){
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->style([
'color' => '#fff',
'backgroundColor' =>$color,
'borderColor' => $color
]);
}else{
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->color('inactive');
}
return $tag;
}
/**
* 生成统计图config
* 折线图或者柱状图
*/
public function chartLineBarConfig($title = null, array $x , array $y){
$yAxisData = [];
$seriesData = [];
$color = [];
if(!isset($y[0])){
$_y = $y;
$y = [0=>$_y];
}
$i = 0;
$tips = '{b0}';
foreach($y as $item) {
//调色盘
$color[] = $item['color'];
//tips
$tips.= '<br/> {a'.$i.'}: {c'.$i.'}'.($item['unit'] ?? '');
//纵坐标
$yAxisData[] = [
'name'=>($item['unit'] ?? ''),
'type' =>'value',
'axisTick' => true,
'alignTicks' => true,
'axisLine' => [
'show' => true,
'lineStyle' => [
'color' => $item['color'] ?? ''
]
],
'axisLabel'=> [
'formatter'=>'{value} '
]
];
//数据
$_series = [
'name' => $item['name'] ?? '',
'data' => $item['data'] ?? [],
'type' => $item['type'] ?? 'line',
'yAxisIndex' => $i,
];
switch($item['type']){
case 'line':
$_series = array_merge($_series, [
'smooth'=> true,
'symbol'=> 'none',
'lineStyle' => [
'color' => $item['color'] ?? ''
],
'areaStyle' => [
'color' => $item['color'] ?? ''
],
]);
break;
case 'bar':
$_series = array_merge($_series, [
]);
break;
}
$seriesData[] = $_series;
$i++;
}
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
// 'formatter' => $tips
],
'grid' => [
'left' => '8%',
'right' => '8%',
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 散点图
*/
public function chartScatterConfig($title = null, array $x , array $y, array $yData = null){
$yAxisData = [];
$seriesData = [];
$color = [];
if($yData){
$yAxisData = [
'type' =>'category',
// 'splitLine'=>[
// 'show'=>true,
// 'lineStyle'=>[
// 'type'=>'dashed'
// ]
// ],
'axisTick' => [
'alignWithLabel'=>true
],
'data'=> $yData
];
}
$seriesData = $y;
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 生成饼状图config
* -todo
*/
public function chartPieConfig(){
return ;
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use Slowlyo\OwlAdmin\Renderers\Operation;
use App\Services\Admin\AdService;
use App\Admin\Components;
use App\Models\Keyword;
use App\Models\Ad;
/**
* 广告管理
*
* @property AdService $service
*/
class AdController extends AdminController
{
protected string $serviceName = AdService::class;
public function list(): Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createButton(),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->labelWidth('80px')->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.ads.id'))
->placeholder(__('admin.id')),
amis()->TextControl('remark', __('admin.ads.remark'))
->placeholder(__('admin.ads.remark')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key'),
amis()->SelectControl('enable', __('admin.ads.is_enable'))
->options([
1=>'开启',0=>'关闭'
]),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.ads.published_at'))->name('published_at'),
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at'),
]),
]))
->columns([
amis()->TableColumn('id', __('admin.ads.id'))->width('50px')->sortable(),
amis()->TableColumn('address', __('admin.ads.address'))->type('mapping')
->map(Keyword::allChildrenOfKey('banner_address')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('sort', __('admin.ads.sort'))->quickEdit(
amis()->NumberControl()->min(0)->saveImmediately(true)
),
amis()->TableColumn('resource', __('admin.ads.resource'))->type('image')->height('50px')->width('150px')->enlargeAble(true),
amis()->TableColumn('remark', __('admin.ads.remark')),
amis()->TableColumn('published_at', __('admin.ads.published_at'))->remark(__('admin.ads.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.ads.is_enable'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form($isEdit = false): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key')->required(true),
Components::make()->imageControl('resource', __('admin.ads.resource'))->required(true),
amis()->TextControl('remark', __('admin.ads.remark')),
Components::make()->sortControl('sort', __('admin.ads.sort')),
amis()->DateTimeControl('published_at', __('admin.ads.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.ads.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.ads.is_enable'))->value(false),
amis()->RadiosControl('jump_type', __('admin.ads.jump_type'))->selectFirst(true)->options(Ad::jumpTypeMap())->required(true),
amis()->TextControl('jump_config.web_link', __('admin.ads.jump_config_arr.web_link'))->visibleOn('this.jump_type == '.Ad::TYPE_WEB)->required(true),
amis()->TextControl('jump_config.app_link', __('admin.ads.jump_config_arr.app_link'))->visibleOn('this.jump_type == '.Ad::TYPE_APP)->required(true),
amis()->GroupControl()->body([
amis()->TextControl('jump_config.mini_id', __('admin.ads.jump_config_arr.mini_id'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
amis()->TextControl('jump_config.mini_link', __('admin.ads.jump_config_arr.mini_link'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([
amis()->TextControl('id', 'ID')->static(),
amis()->TextControl('created_at', __('admin.created_at'))->static(),
amis()->TextControl('updated_at', __('admin.updated_at'))->static()
]);
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Controllers\AdminRoleController as AdminRoleBaseController;
class AdminRoleController extends AdminRoleBaseController
{
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filterTogglable(false)
->itemCheckableOn('${id !== 1}')
->columns([
amis()->TableColumn()->label('ID')->name('id')->sortable(),
amis()->TableColumn()->label(__('admin.admin_role.name'))->name('name'),
amis()->TableColumn()->label(__('admin.admin_role.slug'))->name('slug')->type('tag'),
amis()->TableColumn()
->label(__('admin.created_at'))
->name('created_at')
->type('datetime')
->sortable(true),
amis()->TableColumn()
->label(__('admin.updated_at'))
->name('updated_at')
->type('datetime')
->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->setPermission()->visibleOn('${slug != "administrator"}'),
$this->rowEditButton(true)->visibleOn('${slug != "administrator"}'),
$this->rowDeleteButton()->visibleOn('${slug != "administrator"}'),
]),
]);
return $this->baseList($crud)->css([
'.tree-full' => [
'overflow' => 'hidden !important',
],
'.cxd-TreeControl > .cxd-Tree' => [
'height' => '100% !important',
'max-height' => '100% !important',
],
]);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\Operation;
use Slowlyo\OwlAdmin\Renderers\SwitchControl;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use App\Services\Admin\AdminUserService;
use Slowlyo\OwlAdmin\Services\AdminRoleService;
use Slowlyo\OwlAdmin\Controllers\AdminController;
/**
* @property AdminUserService $service
*/
class AdminUserController extends AdminController
{
protected string $serviceName = AdminUserService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body(
amisMake()->TextControl('keyword', __('admin.keyword'))
->size('md')
->placeholder(__('admin.admin_user.search_username'))
))
->quickSaveItemApi(admin_url('quick-edit/admin_users/$id'))
->itemCheckableOn('${id !== 1}')
->columns([
amisMake()->TableColumn('id', 'ID')->sortable(),
amisMake()->TableColumn('avatar', __('admin.admin_user.avatar'))->type('avatar')->src('${avatar}'),
amisMake()->TableColumn('username', __('admin.username')),
amisMake()->TableColumn('name', __('admin.admin_user.name')),
amisMake()->TableColumn('roles', __('admin.admin_user.roles'))->type('each')->items(
amisMake()->Tag()->label('${name}')->className('my-1')
),
amisMake()->TableColumn('lock', __('admin.admin_user.lock'))->quickEdit(SwitchControl::make()->saveImmediately(true)->mode('inline')->disabledOn('${id === 1}')),
amisMake()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(true)->visibleOn('${id != 1}'),
//单独修改密码
$this->editPassword()->visibleOn('${id != 1}'),
$this->rowDeleteButton()->visibleOn('${id != 1}'),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
amisMake()->ImageControl('avatar', __('admin.admin_user.avatar'))->receiver($this->uploadImagePath()),
amisMake()->TextControl('name', __('admin.admin_user.name'))->required(),
amisMake()->TextControl('username', __('admin.username'))->required(),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->SelectControl('roles', __('admin.admin_user.roles'))
->searchable()
->multiple()
->labelField('name')
->valueField('id')
->joinValues(false)
->extractValue()
->options(AdminRoleService::make()->query()->get(['id', 'name'])),
SwitchControl::make()->name('lock')->label(__('admin.admin_user.lock'))->value(false),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
public function editPassword()
{
return amisMake()->DialogAction()->icon('fa-regular fa-lightbulb')->label(__('admin.admin_user.edit_password'))->level('link')->dialog(
amisMake()->Dialog()->title(__('admin.admin_user.edit_password'))->body([
amisMake()->Form()->title('')
->api([
'method'=>'PUT',
'url'=> admin_url('system/admin_users/$id')
])
->body([
amisMake()->TextControl('id')->value('${id}')->hidden(true),
amisMake()->TextControl('username')->value('${username}')->hidden(true),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6]),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6]),
]),
])->size('md')
);
}
}

View File

@ -0,0 +1,109 @@
<?php
namespace App\Admin\Controllers;
use App\Casts\Storage;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\ArticleService;
use App\Admin\Components;
use App\Models\Keyword;
use App\Traits\CustomActionTrait;
class ArticleController extends AdminController
{
use CustomActionTrait;
protected string $serviceName = ArticleService::class;
public function list():Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createTypeButton('drawer', 'xl'),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.articles.id'))
->placeholder(__('admin.id')),
amis()->TextControl('title', __('admin.articles.title'))
->placeholder(__('admin.articles.title')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->SelectControl('enable', __('admin.articles.is_enable'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->SelectControl('recommend', __('admin.articles.is_recommend'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->InputDatetimeRange()->label(__('admin.articles.published_at'))->name('published_at'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at')->columnRatio(6),
]),
]))
->itemBadge([//行角标
'text' => __('admin.articles.is_recommend'),
'mode' => 'ribbon',
'position' => 'top-left',
'badgeLevel' => 'danger',
'visibleOn' => '${is_recommend > 0}',
'size' => 15
])
->columns([
amis()->TableColumn('id', __('admin.id'))->sortable(true),
amis()->TableColumn('title', __('admin.articles.title'))->width('300px'),
amis()->TableColumn('category', __('admin.articles.category'))->type('mapping')
->map(Keyword::allChildrenOfKey('article_category')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('tags', __('admin.articles.tags'))->type('mapping')->map(Keyword::tagsMap('article_tag')),
amis()->TableColumn('cover', __('admin.articles.cover'))->type('image')->height('50px')->width('50px')->enlargeAble(true),
amis()->TableColumn('published_at', __('admin.articles.published_at'))->remark(__('admin.articles.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.articles.is_enable'))->type('switch'),
amis()->TableColumn('is_recommend', __('admin.articles.is_recommend'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->rowEditTypeButton('drawer', 'xl'),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->panelClassName('px-0')->body([
amis()->Grid()->columns([
amis()->Wrapper()->body([
amis()->TextControl('title', __('admin.articles.title'))->required(true),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
Components::make()->cropImageControl('cover', __('admin.articles.cover')),
Components::make()->sortControl('sort', __('admin.articles.sort')),
amis()->DateTimeControl('published_at', __('admin.articles.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.articles.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.articles.is_enable'))->value(false),
amis()->SwitchControl('is_recommend', __('admin.articles.is_recommend'))->value(false),
Components::make()->fileControl('appendixes', __('admin.articles.appendixes'), '.xsl,.xlsx,.txt,.doc,.docx,.pdf,.pptx'),
])->md(4),
amis()->Wrapper()->body([
Components::make()->fuEditorControl('content', __('admin.articles.content')),
])->md(8)
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;
use Slowlyo\OwlAdmin\Models\AdminUser;
use Slowlyo\OwlAdmin\Controllers\AuthController as AdminAuthController;
use Illuminate\Support\Facades\Hash;
class AuthController extends AdminAuthController
{
public function login(Request $request)
{
if (Admin::config('admin.auth.login_captcha')) {
if (!$request->has('captcha')) {
return $this->response()->fail(__('admin.required', ['attribute' => __('admin.captcha')]));
}
if (strtolower(cache()->pull($request->sys_captcha)) != strtolower($request->captcha)) {
return $this->response()->fail(__('admin.captcha_error'));
}
}
try {
$validator = Validator::make($request->all(), [
'username' => 'required',
'password' => 'required',
], [
'username' . '.required' => __('admin.required', ['attribute' => __('admin.username')]),
'password.required' => __('admin.required', ['attribute' => __('admin.password')]),
]);
if ($validator->fails()) {
abort(Response::HTTP_BAD_REQUEST, $validator->errors()->first());
}
$adminModel = Admin::config("admin.auth.model", AdminUser::class);
$user = $adminModel::query()->where('username', $request->username)->first();
if($user && $user->lock){
abort(Response::HTTP_BAD_REQUEST, '您的账号已被锁定,需要联系超级管理员解锁。');
}else{
if ($user && Hash::check($request->password, $user->password)) {
$module = Admin::currentModule(true);
$prefix = $module ? $module . '.' : '';
$token = $user->createToken($prefix . 'admin')->plainTextToken;
return $this->response()->success(compact('token'), __('admin.login_successful'));
}
abort(Response::HTTP_BAD_REQUEST, __('admin.login_failed'));
}
} catch (\Exception $e) {
return $this->response()->fail($e->getMessage());
}
}
}

View File

@ -0,0 +1,282 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Http\JsonResponse;
use Slowlyo\OwlAdmin\Renderers\Card;
use Slowlyo\OwlAdmin\Renderers\Flex;
use Slowlyo\OwlAdmin\Renderers\Html;
use Slowlyo\OwlAdmin\Renderers\Grid;
use Slowlyo\OwlAdmin\Renderers\Chart;
use Slowlyo\OwlAdmin\Renderers\Image;
use Slowlyo\OwlAdmin\Renderers\Action;
use Slowlyo\OwlAdmin\Renderers\Custom;
use Slowlyo\OwlAdmin\Renderers\Wrapper;
use Illuminate\Http\Resources\Json\JsonResource;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class HomeController extends AdminController
{
public function index(): JsonResponse|JsonResource
{
$page = $this->basePage()->css($this->css())->body([
Grid::make()->columns([
$this->frameworkInfo()->md(5),
Flex::make()->items([
$this->pieChart(),
$this->cube(),
]),
]),
Grid::make()->columns([
$this->lineChart()->md(8),
Flex::make()->className('h-full')->items([
$this->clock(),
$this->hitokoto(),
])->direction('column'),
]),
]);
return $this->response()->success($page);
}
/**
* 一言
*/
public function hitokoto()
{
return Card::make()
->className('h-full clear-card-mb')
->body(
Custom::make()->html(<<<HTML
<div class="h-full flex flex-col mt-5 py-5 px-7">
<div>『</div>
<div class="flex flex-1 items-center w-full justify-center" id="hitokoto">
<a class="text-dark" href="#" id="hitokoto_text" target="_blank"></a>
</div>
<div class="flex justify-end">』</div>
</div>
<div class="flex justify-end mt-3">
——&nbsp;
<span id="hitokoto_from_who"></span>
<span>「</span>
<span id="hitokoto_from"></span>
<span>」</span>
</div>
HTML
)->onMount(<<<JS
fetch('https://v1.hitokoto.cn?c=i')
.then(response => response.json())
.then(data => {
const hitokoto = document.querySelector('#hitokoto_text')
hitokoto.href = `https://hitokoto.cn/?uuid=\${data.uuid}`
hitokoto.innerText = data.hitokoto
document.querySelector('#hitokoto_from_who').innerText = data.from_who
document.querySelector('#hitokoto_from').innerText = data.from
})
.catch(console.error)
JS
)
);
}
public function clock(): Card
{
return Card::make()->className('h-full bg-blingbling')->header([
'title' => '时钟',
])->body([
Custom::make()
->name('clock')
->html('<div id="clock" class="text-4xl"></div><div id="clock-date" class="mt-5"></div>')
->onMount(<<<JS
const clock = document.getElementById('clock');
const tick = () => {
clock.innerHTML = (new Date()).toLocaleTimeString();
requestAnimationFrame(tick);
};
tick();
const clockDate = document.getElementById('clock-date');
clockDate.innerHTML = (new Date()).toLocaleDateString();
JS
),
]);
}
public function frameworkInfo(): Card
{
return Card::make()->className('h-96')->body(
Wrapper::make()->className('h-full')->body([
Flex::make()->className('h-full')->direction('column')->justify('center')->alignItems('center')->items([
Image::make()->src(url(config('admin.logo'))),
Wrapper::make()->className('text-3xl mt-9')->body(config('admin.name')),
Flex::make()->className('w-64 mt-5')->justify('space-around')->items([
Action::make()
->level('link')
->label('GitHub')
->blank(true)
->actionType('url')
->blank(true)
->link('https://github.com/slowlyo/owl-admin'),
Action::make()
->level('link')
->label('OwlAdmin 文档')
->blank(true)
->actionType('url')
->link('http://doc.owladmin.com'),
Action::make()
->level('link')
->label('Amis 文档')
->blank(true)
->actionType('url')
->link('https://aisuda.bce.baidu.com/amis/zh-CN/docs/index'),
]),
]),
])
);
}
public function pieChart(): Card
{
return Card::make()->className('h-96')->body(
Chart::make()->height(350)->config("{
backgroundColor:'',
tooltip: { trigger: 'item' },
legend: { bottom: 0, left: 'center' },
series: [
{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: {
label: { show: true, fontSize: '40', fontWeight: 'bold' }
},
labelLine: { show: false },
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}
]
}")
);
}
public function lineChart(): Card
{
$randArr = function () {
$_arr = [];
for ($i = 0; $i < 7; $i++) {
$_arr[] = random_int(10, 200);
}
return '[' . implode(',', $_arr) . ']';
};
$random1 = $randArr();
$random2 = $randArr();
$chart = Chart::make()->height(380)->className('h-96')->config("{
backgroundColor:'',
title:{ text: '会员增长情况', },
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
grid:{ left: '7%', right:'3%', top: 60, bottom: 30, },
legend: { data: ['访问量','注册量'] },
series: [
{ name: '访问量', data: {$random1}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
{ name:'注册量', data: {$random2}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
]}");
return Card::make()->className('clear-card-mb')->body($chart);
}
public function cube(): Card
{
return Card::make()->className('h-96 ml-4 w-8/12')->body(
Html::make()->html(<<<HTML
<style>
.cube-box{ height: 300px; display: flex; align-items: center; justify-content: center; }
.cube { width: 100px; height: 100px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite; }
.cube:after {
content: '';
width: 100%;
height: 100%;
box-shadow: 0 0 50px rgba(0, 0, 0, 0.2);
position: absolute;
transform-origin: bottom;
transform-style: preserve-3d;
transform: rotateX(90deg) translateY(50px) translateZ(-50px);
background-color: rgba(0, 0, 0, 0.1);
}
.cube div {
background-color: rgba(64, 158, 255, 0.7);
position: absolute;
width: 100%;
height: 100%;
border: 1px solid rgb(27, 99, 170);
box-shadow: 0 0 60px rgba(64, 158, 255, 0.7);
}
.cube div:nth-child(1) { transform: translateZ(-50px); animation: shade 10s -5s linear infinite; }
.cube div:nth-child(2) { transform: translateZ(50px) rotateY(180deg); animation: shade 10s linear infinite; }
.cube div:nth-child(3) { transform-origin: right; transform: translateZ(50px) rotateY(270deg); animation: shade 10s -2.5s linear infinite; }
.cube div:nth-child(4) { transform-origin: left; transform: translateZ(50px) rotateY(90deg); animation: shade 10s -7.5s linear infinite; }
.cube div:nth-child(5) { transform-origin: bottom; transform: translateZ(50px) rotateX(90deg); background-color: rgba(0, 0, 0, 0.7); }
.cube div:nth-child(6) { transform-origin: top; transform: translateZ(50px) rotateX(270deg); }
@keyframes rotate {
0% { transform: rotateX(-15deg) rotateY(0deg); }
100% { transform: rotateX(-15deg) rotateY(360deg); }
}
@keyframes shade { 50% { background-color: rgba(0, 0, 0, 0.7); } }
</style>
<div class="cube-box">
<div class="cube">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
HTML
)
);
}
private function css(): array
{
return [
'.clear-card-mb' => [
'margin-bottom' => '0 !important',
],
'.cxd-Image' => [
'border' => '0',
],
'.bg-blingbling' => [
'color' => '#fff',
'background' => 'linear-gradient(to bottom right, #2C3E50, #FD746C, #FF8235, #ffff1c, #92FE9D, #00C9FF, #a044ff, #e73827)',
'background-repeat' => 'no-repeat',
'background-size' => '1000% 1000%',
'animation' => 'gradient 60s ease infinite',
],
'@keyframes gradient' => [
'0%{background-position:0% 0%}
50%{background-position:100% 100%}
100%{background-position:0% 0%}',
],
'.bg-blingbling .cxd-Card-title' => [
'color' => '#fff',
],
];
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Traits\UploadTrait;
class IndexController extends AdminController
{
use UploadTrait;
}

View File

@ -0,0 +1,72 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\KeywordService;
use App\Admin\Components;
use Illuminate\Http\Request;
class KeywordController extends AdminController
{
protected string $serviceName = KeywordService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
//去掉分页-start
->loadDataOnce(true)
->footerToolbar([])
//去掉分页-end
->headerToolbar([
$this->createButton(true),
$this->exportAction(),
amis('reload')->align('right'),
amis('filter-toggler')->align('right'),
])
->filter($this->baseFilter()->body([
amis()->TextControl('name', __('admin.keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name')),
amis()->TextControl('parent_name', __('admin.keywords.parent_keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name'))
]
))
->columns([
// TableColumn::make()->name('id')->label('ID')->sortable(true),
TableColumn::make()->name('name')->label('名称'),
TableColumn::make()->name('key')->label('KEY')->copyable(true),
TableColumn::make()->name('value')->label('值'),
TableColumn::make()->name('sort')->label('排序'),
TableColumn::make()->name('created_at')->label('创建时间')->type('datetime')->sortable(true),
amisMake()->Operation()->label(__('admin.actions'))->buttons([
//按钮权限示例;
// amis()->action()->label('判断权限')->permission('keywords.custom', amis()->TextControl()->hidden()),
$this->rowEditButton(true),
$this->rowDeleteButton(),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list')),
TextControl::make()->name('name')->label('名称')->required(true),
TextControl::make()->name('key')->label('KEY')->required(true),
TextControl::make()->name('value')->label('值'),
amisMake()->NumberControl()->name('sort')->value(0)->min()->label('排序'),
]);
}
public function getTreeList(Request $request){
return $this->service->getTree();
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Slowlyo\OwlAdmin\Renderers\Tab;
use Slowlyo\OwlAdmin\Renderers\Tabs;
use Slowlyo\OwlAdmin\Renderers\Alert;
use Slowlyo\OwlAdmin\Renderers\InputKV;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class SettingController extends AdminController
{
public function index()
{
$page = $this->basePage()->body([
$this->form(),
]);
return $this->response()->success($page);
}
public function form()
{
return $this->baseForm(false)
->redirect('')->labelWidth('200px')
->api($this->getStorePath())
->data(settings()->all())
->body(
Tabs::make()->tabs([
Tab::make()->title('上传设置')->body([
amis()->RadiosControl('upload_disk', '上传驱动')->options([
'public'=>'本地存储',
'oss' => '阿里云OSS',
])->value('public')->required(true),
amis()->TextControl('oss_config.access_key_id', '阿里云AccessKeyId')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.access_key_secret', '阿里云AccessKeySecret')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.bucket', '对象存储Bucket')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: my-bucket'),
amis()->TextControl('oss_config.endpoint', '对象存储endpoint')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: oss-cn-shanghai.aliyuncs.com'),
amis()->TextControl('oss_config.domain', '自有域名')->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('填写即启用 示例: my-domain.com'),
amis()->SwitchControl('oss_config.use_ssl', '开启SSL')->value(false)->visibleOn('${upload_disk == "oss"}'),
]),
])
);
}
public function store(Request $request)
{
$data = $request->only([
'upload_disk',
'oss_config'
]);
//上传设置-修改env文件内配置;
if(!empty($data['upload_disk'])){
$envData['FILESYSTEM_DISK'] = $data['upload_disk'];
if($envData['FILESYSTEM_DISK'] == 'oss'){//如果设置为OSS驱动,则配置env变量
$envData['OSS_ACCESS_KEY_ID'] = Arr::get($data['oss_config'], 'access_key_id');
$envData['OSS_ACCESS_KEY_SECRET'] = Arr::get($data['oss_config'], 'access_key_secret');
$envData['OSS_BUCKET'] = Arr::get($data['oss_config'], 'bucket');
$envData['OSS_ENDPOINT'] = Arr::get($data['oss_config'], 'endpoint');
$envData['OSS_DOMAIN'] = Arr::get($data['oss_config'], 'domain');
if(!empty($envData['OSS_DOMAIN'])){
$envData['OSS_CNAME'] = 'true';
}else{
$envData['OSS_CNAME'] = 'false';
}
$envData['OSS_SSL'] = Arr::get($data['oss_config'], 'use_ssl') ? 'true':'false';
}
$envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
$contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
$contentArray->transform(function ($item) use ($envData){
foreach ($envData as $key => $value){
if(str_contains($item, $key)){
return $key . '=' . $value;
}
}
return $item;
});
$content = implode("\n", $contentArray->toArray());
\File::put($envPath, $content);
}
return settings()->adminSetMany($data);
}
}

View File

@ -0,0 +1,9 @@
<?php
use Slowlyo\OwlAdmin\Admin;
// Admin::styles([
// '.cxd-Panel-heading { border-width: 0; background: #4080ffc7 !important; }',
// // '.cxd-Panel {box-shadow: none; }',
// '.cxd-Panel-title { color:white;font-size: 16px; }'
// ]);

View File

@ -0,0 +1,43 @@
<?php
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
Route::group([
'domain' => config('admin.route.domain'),
'prefix' => config('admin.route.prefix'),
'middleware' => config('admin.route.middleware'),
], function (Router $router) {
$router->group([
'prefix' => 'api',
], function (Router $router) {
$router->get('keywords/tree-list', '\App\Admin\Controllers\KeywordController@getTreeList')->name('api.keywords.tree-list');
});
$router->resource('index', \App\Admin\Controllers\HomeController::class);
$router->post('login', [App\Admin\Controllers\AuthController::class, 'login']);
$router->resource('system/admin_users', App\Admin\Controllers\AdminUserController::class);
$router->post('quick-edit/admin_users/{admin_user}',[\App\Admin\Controllers\AdminUserController::class, 'update']);
$router->get('system/admin_roles', [App\Admin\Controllers\AdminRoleController::class, 'index']);
$router->resource('system/settings', \App\Admin\Controllers\SettingController::class);
$router->resource('system/keywords', \App\Admin\Controllers\KeywordController::class);
$router->resource('articles', \App\Admin\Controllers\ArticleController::class);
$router->resource('ads', \App\Admin\Controllers\AdController::class);
//修改上传
$router->post('upload_file', [\App\Admin\Controllers\IndexController::class, 'uploadFile']);
$router->post('upload_image', [\App\Admin\Controllers\IndexController::class, 'uploadImage']);
$router->post('upload_rich', [\App\Admin\Controllers\IndexController::class, 'uploadRich']);
$router->post('start_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'startChunk']);
$router->post('save_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'saveChunk']);
$router->post('finish_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'finishChunk']);
});

View File

@ -0,0 +1,45 @@
<?php
namespace App\Casts;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage as StorageFacades;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* 转换文件存储路径
*
* get: 返回全路径
* set: 原样保存
*/
class Storage implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return array
*/
public function get($model, $key, $value, $attributes)
{
return $value ? (Str::startsWith($value, ['http://', 'https://']) ? $value : StorageFacades::disk(Admin::config('admin.upload.disk'))->url($value)) : '';
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
return $value;
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

85
app/Models/Ad.php 100644
View File

@ -0,0 +1,85 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Ad extends Model
{
use HasFactory;
use Filterable;
public const TYPE_OFF = 0; //无跳转
public const TYPE_WEB = 1; //网页跳转
public const TYPE_APP = 2; //应用跳转
public const TYPE_MINI = 3;//小程序跳转
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'published_at' => 'datetime',
'is_enable' => 'boolean',
'jump_config' => 'array',
];
protected $fillable = [
'resource',
'address',
'remark',
'published_at',
'is_enable',
'sort',
'jump_type',
'jump_config',
];
public static function jumpTypeMap() :array
{
return [
self::TYPE_WEB => '网页跳转',
self::TYPE_APP => '应用跳转',
self::TYPE_MINI => '小程序跳转',
self::TYPE_OFF => '无跳转',
];
}
public static function jumpTypeMapLabel()
{
return [
self::TYPE_OFF => "<span class='label'>无跳转</span>",
self::TYPE_WEB => "<span class='label label-info'>网页跳转</span>",
self::TYPE_APP => "<span class='label label-warning'>应用跳转</span>",
self::TYPE_MINI => "<span class='label label-green'>小程序跳转</span>",
'*'=>'其他:${jump_type}'
];
}
public static function typeMapLabel()
{
return [
self::TYPE_IN => "<span class='label label-info'>入住缴费</span>",
self::TYPE_CONTINUE => "<span class='label label-warning'>续住缴费</span>",
self::TYPE_EXIT => "<span class='label label-danger'>离开结算</span>",
'*'=>'其他:${live_in}'
];
}
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Article extends Model
{
use HasFactory;
use Filterable;
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $appends = ['tags'];
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s',
'updated_at' => 'datetime:Y-m-d H:i:s',
'published_at' => 'datetime:Y-m-d H:i:s',
'is_enable' => 'boolean',
'is_recommend' => 'boolean',
'appendixes' => 'array',
];
protected $fillable = [
'title',
'content',
'cover',
'category',
't_ids',
'published_at',
'is_enable',
'is_recommend',
'sort',
'appendixes',
];
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('is_recommend', 'desc')
->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
protected function tags():Attribute
{
return Attribute::make(
get: fn($value) => $this->t_ids ? explode(',', $this->t_ids) : [],
);
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models\Filters;
use Illuminate\Support\Arr;
use EloquentFilter\ModelFilter;
class AdFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 备注
*/
public function remark($remark)
{
return $this->where('remark','like', '%'.$remark.'%');
}
/**
* 位置
*/
public function address($address)
{
return $this->where('address', $address);
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use Illuminate\Support\Arr;
class ArticleFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 标题
*/
public function title($title)
{
return $this->where('title','like', '%'.$title.'%');
}
/**
* 获取分类下的文章
*/
public function category($category)
{
return $this->where('category', $category);
}
/**
* 查询带有标签的文章
*/
public function tIds($tIds){
$tIds = explode(',',$tIds);
return $this->where(function($q) use ($tIds) {
foreach ($tIds as $tId) {
$q->whereRaw("FIND_IN_SET('".$tId."',t_ids)");
}
});
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
public function recommend($recommend){
return $this->where('is_recommend', $recommend);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use App\Models\Keyword;
class KeywordFilter extends ModelFilter
{
/**
* 关键字
*/
public function name($name)
{
return $this->where('name','like', '%'.$name.'%')
->orWhere('key','like', '%'.$name.'%');
}
public function parentName($parent_name)
{
if(request('has_owner', 1)){
$this->where(function($q) use ($parent_name){
$q->where('name','like', '%'.$parent_name.'%')
->orWhere('key','like', '%'.$parent_name.'%');
});
}
return $this->orWhere('path','like', '%-'.
Keyword::where('name','like', '%'.$parent_name.'%')->orWhere('key','like', '%'.$parent_name.'%')->value('id')
. '-%' ?? '');
}
}

View File

@ -0,0 +1,76 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Admin\Components;
use Illuminate\Support\Str;
class Keyword extends Model
{
use HasFactory;
use Filterable;
protected $fillable = ['name', 'key', 'value', 'parent_id', 'parent_key', 'path', 'sort', 'lv'];
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected static function boot()
{
parent::boot();
// 监听 Keyword 的创建事件,用于初始化 path 和 lv 字段值
static::saving(function ($keyword) {
// 如果创建的是一个根类目
if (! $keyword->parent_id) {
// 将层级设为 1
$keyword->lv = 1;
// 将 path 设为 -
$keyword->path = '-';
if(empty($keyword->key)){
$keyword->key = Str::quickRandom($length = 16);
}
} else {
// 将层级设为父类目的层级 + 1
$keyword->lv = $keyword->parent->lv + 1;
$keyword->parent_key = $keyword->parent->key;
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
$keyword->path = $keyword->parent->path.$keyword->parent_id.'-';
//当前key是否为空
if(empty($keyword->key)){
$keyword->key = $keyword->parent_key . '_' . (self::where('parent_key', $keyword->parent_key)->count() + 1);
}
}
});
}
public function parent()
{
return $this->belongsTo(static::class, 'parent_id');
}
public function children()
{
return $this->hasMany(static::class, 'parent_id');
}
public function scopeAllChildrenOfKey($q, $parentKey)
{
$q->where('path','like', '%-'.
static::where('key', $parentKey)->value('id')
. '-%' ?? '');
}
public static function tagsMap(String $key)
{
$mapArr = [];
self::query()->where('parent_key', $key)->get()->map(function($item) use (&$mapArr){
$mapArr[$item->id] = Components::make()->keywordsTag($item->name, $item->value);
});
return $mapArr;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot()
{
\Schema::defaultStringLength(191);
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class QueryLoggerServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
if (! config('app.debug')) {
return;
}
$this->app['events']->listen([
QueryExecuted::class,
TransactionBeginning::class,
TransactionCommitted::class,
TransactionRolledBack::class,
], function ($event) {
Log::debug(match (true) {
$event instanceof TransactionBeginning => 'begin transaction',
$event instanceof TransactionCommitted => 'commit transaction',
$event instanceof TransactionRolledBack => 'rollback transaction',
default => $this->prepareSql($event),
});
});
}
/**
* @param \Illuminate\Database\Events\QueryExecuted $query
* @return string
*/
protected function prepareSql(QueryExecuted $query): string
{
$sql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
$bindings = $query->connection->prepareBindings($query->bindings);
if (count($bindings)) {
$sql = vsprintf($sql, array_map([$query->connection->getPdo(), 'quote'], $bindings));
}
return sprintf('[%s] %s', $this->formatDuration($query->time), $sql);
}
/**
* @param float $milliseconds
* @return string
*/
protected function formatDuration($milliseconds): string
{
return match (true) {
$milliseconds >= 1000 => round($milliseconds / 1000, 2).'s',
$milliseconds < 0.01 => round($milliseconds * 1000).'μs',
default => $milliseconds.'ms',
};
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace App\Services\Admin;
use App\Models\Ad;
use App\Models\Filters\AdFilter;
use App\Traits\UploadTrait;
use Illuminate\Support\Arr;
/**
* @method Ad getModel()
* @method Ad|\Illuminate\Database\Query\Builder query()
*/
class AdService extends BaseService
{
use UploadTrait;
protected string $modelName = Ad::class;
protected string $modelFilterName = AdFilter::class;
protected bool $modelSortAble = true;
public function store($data): bool
{
$columns = $this->getTableColumns();
$model = $this->getModel();
$isEnable = Arr::get($data, 'is_enabled');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt)) {
$data['published_at'] = now();
}
if(isset($data['resource'])){
$data['resource'] = $this->saveImage('resource', 'ads/resource')[0];
}
//处理跳转配置
$jumpType = Arr::get($data, 'jump_type');
if($jumpType !== null){
switch($jumpType){
case Ad::TYPE_OFF:
$data['jump_config'] = null;
break;
case Ad::TYPE_WEB:
$data['jump_config'] = Arr::only($data['jump_config'], 'web_link');
break;
case Ad::TYPE_APP:
$data['jump_config'] = Arr::only($data['jump_config'], 'app_link');;
break;
case Ad::TYPE_MINI:
$data['jump_config'] = Arr::only($data['jump_config'], ['mini_id', 'mini_link']);;
break;
}
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
$isEnable = Arr::get($data, 'is_enable');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt) && empty($model->published_at)) {
$data['published_at'] = now();
}
if(isset($data['resource'])){
$data['resource'] = $this->saveImage('resource', 'ads/resource')[0];
}
//处理跳转配置
$jumpType = Arr::get($data, 'jump_type');
if($jumpType !== null){
switch($jumpType){
case Ad::TYPE_OFF:
$data['jump_config'] = null;
break;
case Ad::TYPE_WEB:
$data['jump_config'] = Arr::only($data['jump_config'], 'web_link');
break;
case Ad::TYPE_APP:
$data['jump_config'] = Arr::only($data['jump_config'], 'app_link');;
break;
case Ad::TYPE_MINI:
$data['jump_config'] = Arr::only($data['jump_config'], ['mini_id', 'mini_link']);;
break;
}
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace App\Services\Admin;
use Illuminate\Support\Arr;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Facades\Hash;
use Slowlyo\OwlAdmin\Models\AdminUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
/**
* @method AdminUser getModel()
* @method AdminUser|Builder query()
*/
class AdminUserService extends BaseService
{
protected string $modelName;
public function __construct()
{
$this->modelName = Admin::adminUserModel();
}
public function getEditData($id): Model|\Illuminate\Database\Eloquent\Collection|Builder|array|null
{
$adminUser = parent::getEditData($id)->makeHidden('password');
$adminUser->load('roles');
return $adminUser;
}
public function store($data): bool
{
if ($this->checkUsernameUnique($data['username'])) {
return $this->setError(__('admin.admin_user.username_already_exists'));
}
if (!data_get($data, 'password')) {
return $this->setError(__('admin.required', ['attribute' => __('admin.password')]));
}
if (!$this->passwordHandler($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->getModel();
return $this->saveData($data, $columns, $model);
}
public function update($primaryKey, $data): bool
{
if ($this->checkUsernameUnique($data['username'], $primaryKey)) {
return $this->setError(__('admin.admin_user.username_already_exists'));
}
if (!$this->passwordHandler($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
return $this->saveData($data, $columns, $model);
}
public function checkUsernameUnique($username, $id = 0): bool
{
return $this->query()
->where('username', $username)
->when($id, fn($query) => $query->where('id', '<>', $id))
->exists();
}
public function updateUserSetting($primaryKey, $data): bool
{
if (!$this->passwordHandler($data, $primaryKey)) {
return false;
}
return parent::update($primaryKey, $data);
}
public function passwordHandler(&$data, $id = null): bool
{
$password = Arr::get($data, 'password');
if ($password) {
if ($password !== Arr::get($data, 'confirm_password')) {
return $this->setError(__('admin.admin_user.password_confirmation'));
}
if ($id) {
if (!Arr::get($data, 'old_password')) {
return $this->setError(__('admin.admin_user.old_password_required'));
}
$oldPassword = $this->query()->where('id', $id)->value('password');
if (!Hash::check($data['old_password'], $oldPassword)) {
return $this->setError(__('admin.admin_user.old_password_error'));
}
}
$data['password'] = bcrypt($password);
unset($data['confirm_password']);
unset($data['old_password']);
}
return true;
}
public function list()
{
$keyword = request()->keyword;
$query = $this
->query()
->with('roles')
->select(['id', 'name', 'username', 'avatar', 'created_at', 'lock'])
->when($keyword, function ($query) use ($keyword) {
$query->where('username', 'like', "%{$keyword}%")->orWhere('name', 'like', "%{$keyword}%");
});
$this->sortable($query);
$items = (clone $query)->paginate(request()->input('perPage', 20))->items();
$total = (clone $query)->count();
return compact('items', 'total');
}
/**
* @param $data
* @param array $columns
* @param AdminUser $model
*
* @return bool
*/
protected function saveData($data, array $columns, AdminUser $model): bool
{
$roles = Arr::pull($data, 'roles');
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
if ($model->save()) {
$model->roles()->sync(Arr::has($roles, '0.id') ? Arr::pluck($roles, 'id') : $roles);
return true;
}
return false;
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Services\Admin;
use App\Models\Article;
use App\Models\Filters\ArticleFilter;
use App\Traits\UploadTrait;
use Illuminate\Support\Arr;
/**
* @method Article getModel()
* @method Article|\Illuminate\Database\Query\Builder query()
*/
class ArticleService extends BaseService
{
use UploadTrait;
protected string $modelName = Article::class;
protected string $modelFilterName = ArticleFilter::class;
protected bool $modelSortAble = true;
public function store($data): bool
{
$columns = $this->getTableColumns();
$model = $this->getModel();
$isEnable = Arr::get($data, 'is_enabled');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt)) {
$data['published_at'] = now();
}
$data['cover'] = $this->saveImage('cover', 'articles/cover')[0] ?? '';
$data['appendixes'] = $this->saveFile('appendixes', 'articles/appendixes');
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
$isEnable = Arr::get($data, 'is_enable');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt) && empty($model->published_at)) {
$data['published_at'] = now();
}
if(isset($data['cover'])){
$data['cover'] = $this->saveImage('cover', 'articles/cover')[0] ?? '';
}
if(isset($data['appendixes'])){
$data['appendixes'] = $this->saveFile('appendixes', 'articles/appendixes');
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Services\Admin;
use Slowlyo\OwlAdmin\Services\AdminService;
/**
* @method Region getModel()
* @method Region|\Illuminate\Database\Query\Builder query()
*/
class BaseService extends AdminService
{
protected array $withRelationships = [];
protected string $modelFilterName = '';
protected bool $modelSortAble = false;
public function getTree()
{
$list = $this->query()->orderByDesc('sort')->get();
$minNum = $list->min('parent_id');
return array2tree($list->toArray(), $minNum);
}
public function getModelFilter()
{
return $this->modelFilterName;
}
public function listQuery()
{
$model = $this->getModel();
$filter = $this->getModelFilter();
$query = $this->query();
if($this->withRelationships){
$query->with($this->withRelationships);
}
if ($filter) {
$query->filter(request()->input(), $filter);
}
if($this->modelSortAble){
$query->sort();
}
$this->sortable($query);
return $query;
}
public function getDetail($id)
{
return $this->query()->with($this->withRelationships)->find($id);
}
}

View File

@ -0,0 +1,116 @@
<?php
namespace App\Services\Admin;
use Illuminate\Support\Arr;
use App\Models\Keyword;
use App\Models\Filters\KeywordFilter;
/**
* @method Keyword getModel()
* @method Keyword|\Illuminate\Database\Query\Builder query()
*/
class KeywordService extends BaseService
{
protected string $modelName = Keyword::class;
protected string $modelFilterName = KeywordFilter::class;
public function getTree()
{
$list = $this->query()->filter(request()->all(), $this->modelFilterName)->orderByDesc('sort')->get();
$minNum = $list->min('parent_id');
return !$list->isEmpty() ? array2tree($list->toArray(), $minNum) :[];
}
public function parentIsChild($id, $pid): bool
{
$parent = $this->query()->find($pid);
do {
if ($parent->parent_id == $id) {
return true;
}
// 如果没有parent 则为顶级 退出循环
$parent = $parent->parent;
} while ($parent);
return false;
}
public function list()
{
return ['items' => $this->getTree()];
}
public function store($data): bool
{
if ($this->hasRepeated($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->getModel();
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
if ($this->hasRepeated($data, $primaryKey)) {
return false;
}
$columns = $this->getTableColumns();
$pid = Arr::get($data, 'parent_id');
if ($pid != 0) {
if ($this->parentIsChild($primaryKey, $pid)) {
$this->setError('父级不允许设置为当前子权限');
return false;
}
}
$model = $this->query()->whereKey($primaryKey)->first();
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function hasRepeated($data, $id = 0): bool
{
$query = $this->query()->when($id, fn($query) => $query->where('id', '<>', $id));
if ((clone $query)->where('key', $data['key'])->exists()) {
$this->setError('KEY重复');
return true;
}
return false;
}
public function delete(string $ids): mixed
{
$ids = explode(',', $ids);
if(count($ids) == 1){
$this->query()->where('path', 'like', '%-'.$ids[0].'-%')->delete();
}
return $this->query()->whereIn('id', $ids)->delete();
}
}

View File

@ -0,0 +1,148 @@
<?php
namespace App\Traits;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Drawer;
use Slowlyo\OwlAdmin\Renderers\Dialog;
use Slowlyo\OwlAdmin\Renderers\DrawerAction;
use Slowlyo\OwlAdmin\Renderers\DialogAction;
use Slowlyo\OwlAdmin\Renderers\LinkAction;
trait CustomActionTrait
{
/**
* 新增按钮
*
* @param string $type
* @param string $size
* @param string $width
*
* @return DialogAction|DrawerAction|LinkAction
*/
protected function createTypeButton(string $type = '', string $size = '', string $width = ''): DialogAction|DrawerAction|LinkAction
{
switch ($type) {
case 'drawer':
$form = $this->form(false)->api($this->getStorePath())->onEvent([]);
$drawer = Drawer::make()->title(__('admin.create'))->body($form)->closeOnOutside();
if($width){
$drawer->width($width);
}else{
$drawer->size($size);
}
$button = DrawerAction::make()->drawer($drawer);
break;
case 'dialog':
$form = $this->form(false)->api($this->getStorePath())->onEvent([]);
$button = DialogAction::make()->dialog(
Dialog::make()->title(__('admin.create'))->body($form)->size($size)
);
break;
default:
$button = LinkAction::make()->link($this->getCreatePath());
break;
}
return $button->label(__('admin.create'))->icon('fa fa-add')->level('primary');
}
/**
* 行编辑按钮
*
* @param string $type
* @param string $size
* @param string $width
*
* @return DialogAction|DrawerAction|LinkAction
*/
protected function rowEditTypeButton(string $type = '', string $size = '', string $width = ''): DialogAction|DrawerAction|LinkAction
{
switch ($type) {
case 'drawer':
$form = $this->form(true)
->api($this->getUpdatePath())
->initApi($this->getEditGetDataPath())
->redirect('')
->onEvent([]);
$drawer = Drawer::make()->title(__('admin.edit'))->body($form)->closeOnOutside();
if($width){
$drawer->width($width);
}else{
$drawer->size($size);
}
$button = DrawerAction::make()->drawer($drawer);
break;
case 'dialog':
$form = $this->form(true)
->api($this->getUpdatePath())
->initApi($this->getEditGetDataPath())
->redirect('')
->onEvent([]);
$button = DialogAction::make()->dialog(
Dialog::make()->title(__('admin.edit'))->body($form)->size($size)
);
break;
default:
$button = LinkAction::make()->link($this->getEditPath());
break;
}
return $button->label(__('admin.edit'))->icon('fa-regular fa-pen-to-square')->level('link');
}
/**
* 行详情按钮
*
* @param string $type
* @param string $size
* @param string $width
*
* @return DialogAction|DrawerAction|LinkAction
*/
protected function rowShowTypeButton(string $type = '', string $size = '', string $width = ''): DialogAction|DrawerAction|LinkAction
{
switch ($type) {
case 'drawer':
$drawer = Drawer::make()->title(__('admin.show'))->name('detail_info')->body($this->detail('$id'))->closeOnOutside();
if($width){
$drawer->width($width);
}else{
$drawer->size($size);
}
//补充详情操作按钮扩展
try{
$actions = $this->detailActions();
}catch(\BadMethodCallException $e){
$actions = [];
}
$drawer->actions($actions);
$button = DrawerAction::make()->drawer($drawer);
break;
case 'dialog':
//补充详情操作按钮扩展
$dialog = Dialog::make()->title(__('admin.show'))->name('detail_info')->body($this->detail('$id'))->size($size);
try{
$actions = $this->detailActions();
}catch(\BadMethodCallException $e){
$actions = [];
}
$dialog->actions($actions);
$button = DialogAction::make()->dialog($dialog);
break;
default:
$button = LinkAction::make()->link($this->getShowPath());
break;
}
return $button->label(__('admin.show'))->icon('fa-regular fa-eye')->level('link');
}
}

View File

@ -0,0 +1,210 @@
<?php
namespace App\Traits;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
trait UploadTrait
{
public function uploadImage()
{
return $this->upload('image');
}
public function uploadFile()
{
return $this->upload();
}
/**
* 富文本内文件上传
*/
public function uploadRich()
{
$fromWangEditor = false;
$file = request()->file('file');
if (!$file) {
$fromWangEditor = true;
$file = request()->file('wangeditor-uploaded-image');
if (!$file) {
$file = request()->file('wangeditor-uploaded-video');
}
}
if (!$file) {
return $this->response()->additional(['errno' => 1])->fail(__('admin.upload_file_error'));
}
$path = $file->store(Admin::config('admin.upload.directory.rich'), Admin::config('admin.upload.disk'));
$link = Storage::disk(Admin::config('admin.upload.disk'))->url($path);
if ($fromWangEditor) {
return $this->response()->additional(['errno' => 0])->success(['url' => $link]);
}
return $this->response()->additional(compact('link'))->success(compact('link'));
}
/**
* 存放临时文件目录,按日期区分;
*/
protected function upload($type = 'file')
{
$file = request()->file('file');
if (!$file) {
return $this->response()->fail(__('admin.upload_file_error'));
}
$path = $file->store(Admin::config('admin.upload.tem_directory.' . $type).'/'.date('Y-m-d'), Admin::config('admin.upload.disk'));
return $this->response()->success(['value' => $path]);
}
public function saveImage($field = 'image', $path)
{
return $this->saveFile($field, $path);
}
/**
* 表单提交时,转存实际目录,并保留上传时文件名称;文件保存全路径
*/
public function saveFile($field = 'file', $path)
{
$file = request()->file($field);
if (!$file) {
$file = request()->get($field);
}
$fileArr = [];
//判断是否多个文件;
if(is_string($file) || isset($file['id'])){
$files = [$file];
}else{
$files = $file;
}
if($files){
foreach($files as $file){
if(is_array($file) && isset($file['state'])){
switch($file['state']){
case 'init':
if(strpos($file['value'], 'temporary') !== false){
$filePath = $path.'/'.$file['name'];
Storage::disk(Admin::config('admin.upload.disk'))->move($file['value'], $filePath);
$fileArr[] = Storage::disk(Admin::config('admin.upload.disk'))->url($filePath);
}else{
$fileArr[] = $file['value'];
}
break;
case 'uploaded':
if(isset($file['name'])){
$filePath = $path.'/'.$file['name'];
if(Str::startsWith($file['value'], ['http://', 'https://'])){
$fileUrl = parse_url($file['value']);
$fileValue = ltrim($fileUrl['path'], '/');
}else{
$fileValue = $file['value'];
}
Storage::disk(Admin::config('admin.upload.disk'))->move($file['value'], $filePath);
$fileArr[] = Storage::disk(Admin::config('admin.upload.disk'))->url($filePath);
}
break;
}
}else{
$fileArr[] = $file;
}
}
}
return $fileArr;
}
/**
* 开始分片上传, 生成唯一ID
*/
public function startChunk()
{
$type = 'file';
$fileName = request()->get('filename', '');
$uploadId = md5(time().$fileName);
//创建临时文件夹
if ( Storage::disk(Admin::config('admin.upload.disk'))->exists(Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId) === false ) {
if ( Storage::disk(Admin::config('admin.upload.disk'))->makeDirectory(Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId) === false ) {
return false;
}
}
return $this->response()->success(['uploadId' => $uploadId]);
}
/**
* 保存分片
*/
public function saveChunk()
{
$type = 'file';
$file = request()->file('file');
$uploadId = request()->get('uploadId');
$partNumber = request()->get('partNumber');
$partSize = request()->get('partSize');
// dd($file);
$fileName = $file->getClientOriginalName();
//判断该分片是否已存在,
$dirPath = Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId;
if(Storage::disk(Admin::config('admin.upload.disk'))->exists($dirPath . '/'.$fileName.'_'.$partNumber)){
return $this->response()->fail(__('admin.upload_file_error'));
}else{
//验证分片大小-todo
$path = $file->storeAs($dirPath, $fileName.'_'.$partNumber, Admin::config('admin.upload.disk'));
$realPath = Storage::disk(Admin::config('admin.upload.disk'))->url($path);
$eTag = md5_file($realPath);
return $this->response()->success(['eTag' => $eTag]);
}
}
/**
* 完成分片
*/
public function finishChunk()
{
$type = 'file';
//合并文件
$fileName = request()->get('filename', '');
$uploadId = request()->get('uploadId', '');
$partList = request()->get('partList', []);
$basePath = Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId;
$realPath = 'chunk/'.$fileName;
//获取分片列表中序号,查看分片是否都完成上传
$partNumberList = Arr::pluck($partList, 'partNumber');
if(max($partNumberList) === count($partNumberList)){
//判断是否已存在同名文件,进行删除
if(Storage::disk(Admin::config('admin.upload.disk'))->exists($realPath)){
$realPath = 'chunk/(1)'.$fileName;
}
for($i = 1; $i<=count($partNumberList); $i++){
$_file = Storage::disk(Admin::config('admin.upload.disk'))->get($basePath.'/'.$fileName.'_'.$i);
Storage::disk(Admin::config('admin.upload.disk'))->append($realPath, $_file, null);
}
//删除分片文件夹
Storage::disk(Admin::config('admin.upload.disk'))->deleteDirectory($basePath);
$value = Storage::disk(Admin::config('admin.upload.disk'))->url($realPath);
return $this->response()->success(['value'=>$value]);
}else{
return $this->response()->fail(__('admin.upload_file_error'));
}
}
}

53
artisan 100644
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php 100644
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
*
!.gitignore

70
composer.json 100644
View File

@ -0,0 +1,70 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.1",
"alphasnow/aliyun-oss-laravel": "^4.7",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.3",
"laravel/tinker": "^2.8",
"rap2hpoutre/fast-excel": "^5.4",
"slowlyo/owl-admin": "^3.5",
"tucker-eric/eloquentfilter": "^3.2"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.1",
"spatie/laravel-ignition": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

6579
composer.lock generated 100644

File diff suppressed because it is too large Load Diff

131
config/admin.php 100644
View File

@ -0,0 +1,131 @@
<?php
return [
// 应用名称
'name' => 'Owl Admin',
// 应用 logo
'logo' => '/admin-assets/logo.png',
// 默认头像
'default_avatar' => '/admin-assets/default-avatar.png',
// 应用安装目录
'directory' => app_path('Admin'),
// 引导文件
'bootstrap' => app_path('Admin/bootstrap.php'),
// 应用路由
'route' => [
'prefix' => 'admin-api',
'domain' => null,
'namespace' => 'App\\Admin\\Controllers',
'middleware' => ['admin'],
// 不包含额外路由, 配置后, 不会追加新增/详情/编辑页面路由
'without_extra_routes' => [
'/dashboard',
],
],
'auth' => [
// 是否开启验证码
'login_captcha' => env('ADMIN_LOGIN_CAPTCHA', true),
// 是否开启认证
'enable' => true,
// 是否开启鉴权
'permission' => true,
// token 有效期 (分钟), 为空则不会过期
'token_expiration' => null,
'guard' => 'admin',
'guards' => [
'admin' => [
'driver' => 'sanctum',
'provider' => 'admin',
],
],
'providers' => [
'admin' => [
'driver' => 'eloquent',
'model' => \Slowlyo\OwlAdmin\Models\AdminUser::class,
],
],
'except' => [
],
],
'upload' => [
'disk' => env("FILESYSTEM_DISK", 'public'),
// 文件上传目录
'directory' => [
'image' => 'images',
'file' => 'files',
'rich' => 'rich',
],
// 临时目录
'tem_directory' => [
'image' => 'temporary/images',
'file' => 'temporary/file',
'rich' => 'temporary/rich',
]
],
'https' => env('ADMIN_HTTPS', false),
// 是否显示 [开发者工具]
'show_development_tools' => env('ADMIN_SHOW_DEVELOPMENT_TOOLS', true),
// 是否显示 [权限] 功能中的自动生成按钮
'show_auto_generate_permission_button' => env('ADMIN_SHOW_AUTO_GENERATE_PERMISSION_BUTTON', true),
// 扩展
'extension' => [
'dir' => base_path('extensions'),
],
'layout' => [
// 浏览器标题, 功能名称使用 %title% 代替
'title' => '%title% | OwlAdmin',
'header' => [
// 是否显示 [刷新] 按钮
'refresh' => true,
// 是否显示 [暗色模式] 按钮
'dark' => true,
// 是否显示 [全屏] 按钮
'full_screen' => true,
// 是否显示 [主题配置] 按钮
'theme_config' => true,
],
/*
* keep_alive 页面缓存黑名单
*
* eg:
* 列表: /user
* 详情: /user/:id
* 编辑: /user/:id/edit
* 新增: /user/create
*/
'keep_alive_exclude' => [],
// 底部信息
'footer' => '<a href="https://github.com/slowlyo/owl-admin" target="_blank">Owl Admin</a>',
],
'database' => [
'connection' => env('ADMIN_DB_CONNECTION') ?? env('DB_CONNECTION', 'mysql'),
],
'models' => [
'admin_user' => \Slowlyo\OwlAdmin\Models\AdminUser::class,
'admin_role' => \Slowlyo\OwlAdmin\Models\AdminRole::class,
'admin_menu' => \Slowlyo\OwlAdmin\Models\AdminMenu::class,
'admin_permission' => \Slowlyo\OwlAdmin\Models\AdminPermission::class,
],
'modules_namespace' => 'AdminModules',
'modules_dir' => base_path('admin-modules'),
'modules' => [
],
];

190
config/app.php 100644
View File

@ -0,0 +1,190 @@
<?php
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'PRC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'zh_CN',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\QueryLoggerServiceProvider::class,
])->toArray(),
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];

115
config/auth.php 100644
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

View File

@ -0,0 +1,71 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

111
config/cache.php 100644
View File

@ -0,0 +1,111 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php 100644
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
config/database.php 100644
View File

@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

View File

@ -0,0 +1,92 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
"oss" => [
"driver" => "oss",
"access_key_id" => env("OSS_ACCESS_KEY_ID"), // 必填, 阿里云的AccessKeyId
"access_key_secret" => env("OSS_ACCESS_KEY_SECRET"), // 必填, 阿里云的AccessKeySecret
"bucket" => env("OSS_BUCKET"), // 必填, 对象存储的Bucket, 示例: my-bucket
"endpoint" => env("OSS_ENDPOINT"), // 必填, 对象存储的Endpoint, 示例: oss-cn-shanghai.aliyuncs.com
"internal" => env("OSS_INTERNAL", null), // 选填, 内网上传地址,填写即启用 示例: oss-cn-shanghai-internal.aliyuncs.com
"domain" => env("OSS_DOMAIN", null), // 选填, 绑定域名,填写即启用 示例: oss.my-domain.com
"is_cname" => env("OSS_CNAME", false), // 选填, 若Endpoint为自定义域名,此项要为true,见:https://github.com/aliyun/aliyun-oss-php-sdk/blob/572d0f8e099e8630ae7139ed3fdedb926c7a760f/src/OSS/OssClient.php#L113C1-L122C78
"prefix" => env("OSS_PREFIX", ""), // 选填, 统一存储地址前缀
"use_ssl" => env("OSS_SSL", false), // 选填, 是否使用HTTPS
"reverse_proxy" => env("OSS_REVERSE_PROXY", false), // 选填, 域名是否使用NGINX代理绑定
"throw" => env("OSS_THROW", true), // 选填, 是否抛出引起错误的异常,默认出现错误时,不抛出异常仅返回false
"options" => [], // 选填, 添加全局配置参数, 示例: [\OSS\OssClient::OSS_CHECK_MD5 => false]
"macros" => [] // 选填, 添加自定义Macro, 示例: [\App\Macros\ListBuckets::class, \App\Macros\CreateBucket::class]
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

54
config/hashing.php 100644
View File

@ -0,0 +1,54 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12),
'verify' => true,
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
'verify' => true,
],
];

131
config/logging.php 100644
View File

@ -0,0 +1,131 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => LOG_USER,
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

126
config/mail.php 100644
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "log", "array", "failover"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
// 'client' => [
// 'timeout' => 5,
// ],
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => null,
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

109
config/queue.php 100644
View File

@ -0,0 +1,109 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [