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.未完待續(還有更多優化之處...前行的道路還很遠!)

 

 

三、注意:


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

 

發佈了32 篇原創文章 · 獲贊 44 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章