Laravel + Laravel-admin 搭建网站后台

本地环境:

laravel版本:

laravel-admin版本:

laravel-admin优秀扩展包!!

一、安装配置Laravel6.11.0


 1.安装

composer create-project --prefer-dist laravel/laravel blog

2.改时区

'timezone' => 'PRC'

3.改语言

'locale' => 'zh-CN'

4.改debug

'debug' => env('APP_DEBUG', true)
APP_DEBUG=true

5.改APP_URL

'url' => env('APP_URL', 'http://test.io'),
APP_URL=http://test.io

6.新增数据库,并修改数据库配置

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test1
DB_USERNAME=root
DB_PASSWORD=root

7.修改日志

laravel5.5+:

'log' => env('APP_LOG', 'daily'),
'log_max_files' => 30,

laravel6+中日志更新了:
所有的应用程序日志系统配置都位于 config/logging.php 配置文件中!!! 

'channels' => ['daily'],
'days' => 30,

8.添加公共函数类

1) 新建文件,文件名任意:
app/Helpers/function.php
2) 在composer.json 中 autoload 增加:

"autoload":{
    ...
    "files":[
        "app/Helpers/function.php"
    ]        
}

3) 打开cmd, 切换到项目目录, 执行命令:

composer dump-auto

就能在任何地方引用函数
视图模板中使用方式:{{ functionName() }}

 二、安装配置laravel-admin1.7.9


1.安装

composer require encore/laravel-admin
php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider"
php artisan admin:install

报错参考: (注意要先把数据库生成的两张表删了)

后台访问地址: 网址/admin/auth/login
数据库默认账号密码: admin admin

2.管理员设置页面, 报错

Disk [admin] not configured, please add a disk config in `config/filesystems.php`.

具体解决方法:
在config/filesystems.php中添加:

'admin' => [
    'driver' => 'local',
    'root' => public_path('uploads'),
    'visibility' => 'public',
    'url' => env('APP_URL').'/uploads',
],

在根目录(public)下新增 uploads/images 文件夹

3.默认让后台左侧菜单展开

打开config/admin.php, 修改layout, 去掉sidebar-collapse, 留下sidebar-mini

4.关闭日志, 清理日志表

1) 在admin.php里:

'operation_log' => [
    'enable' => false,
    ...
]

2) TRUNCATE admin_operation_log;

5.换皮肤

在admin.php里:

'skin' => 'skin-yellow',

6.去掉搜索框

在admin.php里:

'enable_menu_search' => false,

7.设置 favicon.ico 图标

在app/Admin/bootstrap.php加入下面的代码来设置网站的favicon:

use Encore\Admin\Admin;
Admin::favicon('/your/favicon/path');

8.快速生成 CURD 页面(注意Windows和Linux命令不同)

要先创建模型 (前提, 要有模型对应的数据表) [备注:如果是用gitbash的话,写法和linux一样]

// linux写法
php artisan admin:make ArticleController --model=App\\Models\\Article
php artisan admin:make CategoryController --model=App\\Models\\Category

9.修改上传图片默认配置

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);
    // }
}

10.覆写内置视图

如果有需要自己修改view,但是不方便直接修改laravel-admin的情况,可以用下面的办法解决:
复制vendor/encore/laravel-admin/views到项目的resources/views/admin,然后在app/Admin/bootstrap.php文件中加入代码:

// 覆盖`admin`命名空间下的视图
app('view')->prependNamespace('admin', resource_path('views/admin'));

11.添加网站设置composer包 - configx!

https://github.com/ichynul/configx

安装步骤:
1) need to install laravel-admin-ext/config first, see https://github.com/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;
            do{
                $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白名单功能等等....

18.未完待续(还有更多优化之处...前行的道路还很远!)

发布了28 篇原创文章 · 获赞 43 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_34248133/article/details/104041921