laravel-admin(二)
话不多说 开干 遇到问题就总结
在config/filesystems.php中添加:
'admin' => [
'driver' => 'local',
'root' => public_path('upload'),
'visibility' => 'public',
'url' => env('APP_URL').'/public/upload/',
],
修改图片 你要不改会查不到图片
在 config/filesystems.php 里面添加一个 admin 磁盘
'disks' => [
'admin' => [
'driver' => 'local',
'root' => public_path('upload'),
'visibility' => 'public',
'url' => env('APP_URL').'/upload',
在.env 填写你的域名
需要在public下面创建个admin的文件夹/upload/images
刷新页面修改头像、
简单使用Laravel-admin管理文章。
先在laravel_admin数据库建立一个文章表 表取名为:article
需要的字段有:
id(设置为主键并自增), title(文章标题,VARCHAT类型长度32),
content(文章内容,TEXT类型), updated_at(修改时间,TIMESTAMP类型),
created_at(创建时间,TIMESTAMP类型)
php artisan admin:make ArticleController --model=App\Article
如果执行失败 先执行下 composer dump-autoload
打开文件app/Admin/routes.php
添加一句代码:
$router->resource('articles', ArticleController::class);
php artisan make:model Models\\Article
会自动生成一个Models 里面多一个Article.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class \Article extends Model
protected $table = 'Article';
}
控制器中会多个ArticleController.php
<?php
namespace App\Admin\Controllers;
use App\Article;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
class ArticleController extends AdminController
* Title for current resource.
* @var string
protected $title = '文章管理';
* Make a grid builder.
* @return Grid
protected function grid()
$grid = new Grid(new Article());
$grid->id('ID')->sortable();
$grid->title('文章标题');
$grid->created_at('创建时间');
$grid->updated_at('修改时间');
return $grid;
* Make a show builder.
* @param mixed $id
* @return Show
protected function detail($id)
$show = new Show(Article::findOrFail($id));
$show->id('文章ID');
$show->title('文章标题');
$show->content('文章内容');
$show->created_at('创建时间');
$show->updated_at('修改时间');
return $show;
* Make a form builder.
* @return Form
protected function form()
$form = new Form(new Article());
$form->text('title','文章标题');
$form->textarea('content','文章内容');
$form->display('id', '文章ID');
$form->display('created_at', '创建时间');
$form->display('updated_at', '修改时间');
return $form;
}
php artisan config:cache 时不时的要清缓存
修改左侧内容 在数据表admin_menu 字段title
修改权限内容 admin_permissions 字段name
操作日志表admin_operation_log
默认让后台左侧菜单展开
打开config/admin.php, 修改layout, 去掉sidebar-collapse, 留下sidebar-mini
关闭日志, 清理日志表
在admin.php里: 改成false
换皮肤 在admin.php里:
'skin' => 'skin-yellow',
去掉搜索框
在admin.php里:
'enable_menu_search' => false,
设置 favicon.ico 图标
在app/Admin/bootstrap.php加入下面的代码来设置网站的favicon:
use Encore\Admin\Admin;
Admin::favicon('/your/favicon/path');
快速生成 CURD 页面(注意Windows和Linux命令不同)
要先创建模型 (前提, 要有模型对应的数据表) [备注:如果是用gitbash的话,写法和linux一样]
// linux写法
php artisan admin:make ArticleController --model=App\\Models\\Article
php artisan admin:make CategoryController --model=App\\Models\\Category
修改上传图片默认配置
1) 增加日期文件夹
2) 重新生成文件名, 不用原文件名
3) 删除原来的图片
图片路径格式:
http://test.io/uploads/images/2020-01-05/310ab8213e850f6e24fd37a0ec85d25d.jpg
只涉及到单张图片, 多图还没弄, 等有那个功能时再弄。
涉及到的文件及方法:
$form->image('avatar', trans('admin.avatar'))->uniqueName();
/vendor/laravel/framework/src/illuminate/Filesystem/FilesystemAdapter.php => putFileAs()
public function putFileAs($path, $file, $name, $options = [])
$stream = fopen($file->getRealPath(), 'r+');
// date file path
$date = date('Y-m-d');
$file_path = public_path('uploads/images/' . $date);
if (!is_dir($file_path)){ mkdir($file_path); }
// Next, we will format the path of the file and store the file using a stream since
// they provide better performance than alternatives. Once we write the file this
// stream will get closed automatically by us so the developer doesn't have to.
$result = $this->put(
$path = trim($path.'/'.$date.'/'.$name, '/'), $stream, $options
if (is_resource($stream)) {
fclose($stream);
return $result ? $path : false;
}
/vendor/encore/laravel-admin/src/Form/Field/UploadField.php => destroy()
public function destroy()
if ($this->retainable) {
return;
if (method_exists($this, 'destroyThumbnail')) {
$this->destroyThumbnail();
// 如果是数组的话暂时不考虑删除, 因为现在还没有多图的功能, 如果有的话再去测试
if (is_array($this->original)) {
return;
$checkOldImgPath = '.'.stristr($this->original, '/uploads');
if (file_exists($checkOldImgPath)) {
unlink($checkOldImgPath);
// 原版, 不好使, 上面为重写, 但是只是删除单个图片
// if ($this->storage->exists($this->original)) {
// $this->storage->delete($this->original);
}
覆写内置视图
如果有需要自己修改view,但是不方便直接修改laravel-admin的情况,可以用下面的办法解决:
复制vendor/encore/laravel-admin/views到项目的resources/views/admin,然后在app/Admin/bootstrap.php文件中加入代码:
// 覆盖`admin`命名空间下的视图
app('view')->prependNamespace('admin', resource_path('views/admin'));
添加网站设置composer包 - configx!
https://github.com/ichynul/configx
安装步骤:
1) need to install laravel-admin-ext/config first, see laravel-admin-extensions/config
说让我们先安装laravel-admin-ext/config,去上面的网址,我先去安装一下
(1) 安装laravel-admin-ext/config:
composer require laravel-admin-ext/config
php artisan migrate
php artisan admin:import config
2) 安装configx:
composer require ichynul/configx
php artisan admin:import configx
添加如下配置到admin.php:
'extensions' => [
'configx' => [
// Set to `false` if you want to disable this extension
'enable' => true,
'tabs' => [
'base' => '基本设置',
// Whether check group permissions.
//if (!Admin::user()->can('confix.tab.base')) {/*hide base tab*/ } .
'check_permission' => false
],
(3) 打开 http:// your-host/admin/configx 这个网址, 然后配置网址, 这个我配置了 5 个字段, 分别是:网站标题,copyright,和在线客服,描述,关键字 (标题不超过30字, 描述80字左右)
(4) 效果如图:
12.添加 HTMLPurifier 做 XSS 安全过滤
1) 安装:
composer require mews/purifier
php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider"
2) 配置:在 config/purifie.php 里
3) 用法:clean($content);
13.添加富文本编辑器CKEditor
1) 安装:
composer require laravel-admin-ext/ckeditor
php artisan vendor:publish --tag=laravel-admin-ckeditor
2) 添加配置:
在admin.php中添加如下代码:
'extensions' => [
'ckeditor' => [
//Set to false if you want to disable this extension
'enable' => true,
// Editor configuration
'config' => [
]
3) 用法:
$form->ckeditor('content', __('内容'))->options(['height' => 500]);
4) 让ckeditor可以上传图片:
(1)添加配置:
在admin.php中添加如何代码: (即上面补充)
'extensions' => [
'ckeditor' => [
//Set to false if you want to disable this extension
'enable' => true,
// Editor configuration
'config' => [
'filebrowserImageUploadUrl' => '/admin/ckeditor/upload?opener=ckeditor&type=images',
'filebrowserUploadMethod' => 'form',
],
(2) 在 /public/vendor/laravel-admin-ext/ckeditor/plugins/image/dialogs/image.js 中搜索并更改 hidden:false
id:"Upload",hidden:!0
//更改为
id:"Upload",hidden:false
(3) 创建控制器: PublicController.php (大致内容如下)
<?php
namespace App\Admin\Controllers;
use Illuminate\Http\Request;
use Encore\Admin\Controllers\AdminController;
class PublicController extends AdminController
* 上传图片大小
* @var int
private $imgSize = 500 * 1024; // 500KB
* 图片上传根路径
* @var string
private $imgDesPath = 'uploads/images/';
* 允许的图片后缀
* @var array
private $imgAllowedExtensions = ["png", "jpg", "gif", "jpeg"];
* CKEditor上传图片
* @author JB.Mony
* @date 2020-01-08
* @param Request $request
* @return string
public function CkUploadImage(Request $request)
$ck = $request->get('CKEditorFuncNum');
if ($request->hasFile('upload')) {
$file = $request->file('upload');
// 验证处理部分,自行发挥
$date = date('Y-m-d');
$dateFilePath = public_path($this->imgDesPath.'/'.$date);
if (!is_dir($dateFilePath)) {
mkdir($dateFilePath);
$destinationPath = '/'.$this->imgDesPath.$date;
$fileName = md5(str_random(15).time()).'.'.$ext;
$url = $destinationPath.'/'.$fileName;
}while(file_exists('.'.$url));
$result = $file->move('.'.$destinationPath, $fileName);
return "<script>window.parent.CKEDITOR.tools.callFunction($ck, '$url', '');</script>";
}
(4) 添加路由:
$router->post('/ckeditor/upload', 'PublicController@CkUploadImage'); // ckeditor
(5) 去掉CSRF认证, 即加入过滤白名单
在 /app/Http/Middleware/VerifyCsrfToken.php 中添加路由白名单:
protected $except = [
'admin/ckeditor/upload'
];
(6) 解决CKeditor上传图片默认设置原始图片高宽的问题:
即->在上传完图片的时候, 显示的是图片的宽和高的默认值, 现在要把默认值去掉!
方法:
在 /public/vendor/laravel-admin-ext/ckeditor/config.js 中添加如下代码:
config.disallowedContent = 'img{width,height};img[width,height]';
(7) 去掉ckeditor上传图片 => "预览" 里的英文字母:
在 /public/vendor/laravel-admin-ext/ckeditor/config.js 中添加如下代码:
config.image_previewText=' ';
(8) 解决编辑器上传图片不能自适应最大宽度:
在 /public/vendor/laravel-admin-ext/ckeditor/contents.css 里第31行添加:
.cke_editable img {
max-width: 100% !important;
}
5) 居中插件 justify_4.1.3.1 这个插件需要下载才可以 (默认是没有的, 即使配置里写了!)
(1) 下载网址:https://ckeditor.com/cke4/addon/justify
(2) 复制下载的justfy文件夹到 /public/vendor/laravel-admin-ext/ckeditor/plugins
(3) 在 /public/vendor/laravel-admin-ext/ckeditor/config.js 中添加:
config.extraPlugins = 'justify';
14.配置中文语言包
在 /resource/lang/zh-CN/admin.php:
用法:
trans('admin.xxoo');
15.报错 http:// test.io/vendor/laravel- admin-ext/row-table/table.css net::ERR_ABORTED 404 (Not Found)
安装 laravel-admin row-table 插件!
composer require ichynul/row-table
php artisan vendor:publish --tag=row-table
16.后台登录页面样式修改
1) 标题字体改为白色:
/public/vendor/laravel-admin/AdminLTE/dist/css/AdminLTE.min.css 里搜索:
.login-logo a,.register-logo a
将其属性颜色改为白色: #fff
2) 修改 form 表单背景颜色
/public/vendor/laravel-admin/AdminLTE/dist/css/AdminLTE.min.css 里搜索:
.login-box-body,.register-box-body
将背景颜色改为: #ffffff8f
3) 修改背景图片:
在 admin.php 里设置: (这个就随意了, 附上我的 ^_^)
'login_background_image' => '/image/bg.jpg',
17.补充性建议,这个就自己发挥吧!
要上线的话, 这个访问路径是肯定不行的, 而且如果输入对了后台的网址, 在没有登录的情况下会自动跳转到后台登录网址, 这个是不可取的...有很多人会去猜网址...如何解决呢, 我有个建议, 如果没有登录的话, 但是访问对了(蒙对了)后台的网址的话, 就直接返回404页面, 还有就是在后台登录页面加一个token作为标识, 如果token不正确的话就返回404, 这个token参数可以随便定义其名称, 我这里也就是举个例子, 也可以定义多个参数, 让不知道的人无法找到, 还可以用IP白名单功能等等....
1.函数使用变化
随着 Laravel 版本的提升,一些函数已经不支持或者不是原来的使用方式了,在这里总结一下:(待补充)
1) 原来的 str_random(15) 函数会报错,如下:
Call to undefined function App\Http\Controllers\Home\str_random()
应该使用如此姿势:
\Str::random(15)
参考链接:https://learnku.com/laravel/t/34844
关于laravel-admin 后台 列表标签背景的使用
$grid->status(trans('alarm.status'))->display(function ($status) {
if ($status==1) {
return "<span class='label bg-red'>未处理</span>";
}elseif ($status==2) {
return "<span class='label bg-yellow'>处理中</span>";
}elseif($status==3) {
return "<span class='label bg-green'>已完成</span>";
}else{
return '异常';
.bg-red .bg-yellow .bg-aqua .bg-blue .bg-light-blue .bg-green,
.bg-navy .bg-teal .bg-olive .bg-lime .bg-orange .bg-fuchsia .bg-purple
.bg-maroon .bg-black
只需把上面的类更换即可,上面的的都是可以使用的
laravel-admin excel导出中文乱码问题
用默认的导出按钮,导出的中文有乱码
在 vendor\encore\laravel-admin\src\Grid\Exporters\CsvExporter.php 中
$headers = [
'Content-Encoding' => 'UTF-8',
'Content-Type' => 'text/csv;charset=UTF-8',
'Content-Disposition' => "attachment; filename=\"$filename\"",
];
//添加的代码
print(chr(0xEF).chr(0xBB).chr(0xBF));
邮件系统
使用Laravel自带SMTP邮件组件实现发送邮件
打开config/mail.php,进行配置
<?php
https://www.jianshu.com/p/8ccb2820df23
https://blog.csdn.net/touxian51552/article/details/85258790?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
return [
//driver用于配置默认的邮件发送驱动
'driver' => env('MAIL_DRIVER', 'smtp'),
//host是邮箱所在主机,比如我们使用163邮箱,对应值是smtp.163.com,使用QQ邮箱的话,对应值是smtp.qq.com
'host' => env('MAIL_HOST', 'smtp.163.com'),
//port用于配置邮箱发送服务端口号,比如一般默认值是25,但如果设置SMTP使用SSL加密,该值为465。
'port' => env('MAIL_PORT', 25),
//from配置项包含address和name,前者表示发送邮箱,后者表示发送邮件使用的用户名。
'from' => ['address' => '423@163.com','name' => '发件人'],
//encryption表示加密类型,可以设置为null表示不使用任何加密,也可以设置为tls或ssl。
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
//username表示邮箱账号
'username' => env('MAIL_USERNAME'),
//password表示上述邮箱登录对应登录密码。注意QQ邮箱的话应该开启POP3|SMTP服务时给的密钥。
'password' => env('MAIL_PASSWORD'),
//sendmail是在设置driver为sendmail时使用,用于指定sendmail命令路径。
'sendmail' => '/usr/sbin/sendmail -bs',
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
'log_channel' => env('MAIL_LOG_CHANNEL'),
];
打开.env文件进行配置
MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=25
MAIL_USERNAME=name@163.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=
发送纯文本邮件
$form->text('title', '提问人名称');
$form->email('email', '提问人');
$form->textarea('content', '提问内容');
$form->text('re_title', '回复标题')->rules('required');
$form->textarea('re_content', '回复内容')->rules('required');
// 在表单提交前调用
$form->submitted(function (Form $form) {
// 在保存前调用,发送邮件
$form->saving(function (Form $form) {
$this->name = $form->email;
$this->retitle=$form->re_title;
$re_content=$form->re_content;
Mail::raw( $re_content, function ($message) {
$message ->to($this->name)->subject($this->retitle);
//保存后回调,更改数据库数据
$form->saved(function (Form $form) {
// 返回的一个错误数组,利用此可以判断是否发送成功
if(count(Mail::failures()) < 1){
$id= $form->model()->id;
$flight = TpInvestEmail::find($id);
$flight->re_email = 1;
$flight->re_time = time();
$flight->save();
else{
$id= $form->model()->id;
$flight = TpInvestEmail::find($id);
$flight->re_email = 0;
$flight->save();
});
常用扩展:富文本,大文件上传,在线视频播放
富文本 百度Ueditor
https://github.com/laravel-admin-extensions/UEditor
大文件上传
https://github.com/laravel-admin-extensions/large-file-upload
关于config/aetherupload里面的配置信息
return [
"ENABLE_EXAMPLE_PAGE" => true, # 启用示例页面,访问域名/aetherupload,生产环境下请将该选项设置为false
"CHUNK_SIZE" => 1 * 1000 * 1000, # 上传时的分块大小(B),默认为1M,越大传输越快,需要小于web服务器和php.ini中设置的上传限值
"UPLOAD_PATH" => storage_path(). DIRECTORY_SEPARATOR . "app".DIRECTORY_SEPARATOR."public".DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR."aetherupload", # 上传目录的本地物理路径
"HEAD_DIR" => "_head", # 指针头文件目录的名称,建议保持默认
"FILE_SUB_DIR" => @date("Ym", time()), #资源文件目录的子目录生成规则,变量或常量均可
"REDIS_KEY" => "aetherupload_file_hashes", #redis中hashes的key名称
"GROUPS" => [ # 分组,可设置多个不同分组,各自拥有独立配置
"file" => [ # 新增分组请尽量使用video、audio等有意义的分组名
"FILE_MAXSIZE" => 0, # 被允许的资源文件大小(MB),0为不限制
"FILE_EXTENSIONS" => "", # 被允许的资源文件扩展名,空为不限制,多个值以逗号分隔
"MIDDLEWARE_PREPROCESS" => [], # 上传预处理时的路由中间件
"MIDDLEWARE_SAVE_CHUNK" => [], # 上传文件分块时的路由中间件
"MIDDLEWARE_DISPLAY" => [], # 文件展示时的路由中间件
"MIDDLEWARE_DOWNLOAD" => [], # 文件下载时的路由中间件