laravel-admin使用问题汇总

记录laravel-admin使用时遇到的问题

  • 如何实现CURD功能?
  • 一对一表关联查询列表?
  • 如何隐藏指定的列?
  • 表单提交如何让某个字段自动完成
  • 表单中的默认值?
  • 如何自定义列表的工具列表?
  • 如何重写默认路由?
  • 如何在原来的管理员增加字段?
  • 模板如何生成URL?
  • 如何添加参数?
  • 如何返回指定字段中的值?
  • 如何配置邮箱发送?
  • 导出CSV乱码处理?
  • demo 0.0.0.0 监听?
  • 后台错误 not configured, please add a disk config in config/filesystems.php

代码块

{{ $var or 'default' }} 模板默认值

php artisan

查看路由表: artisan route:list

待试验

laravel-admin换皮肤

使用过的composer包

"require": {
...
    "laravel-admin-ext/summernote": "^1.0",
    "spatie/eloquent-sortable": "^3.4",
    "spatie/laravel-backup": "^5.0"
...
}
"require-dev": {
...
    "barryvdh/laravel-debugbar": "^3.0",
...
}

参考资料

laravel-admin
官网-laravel-admin
官方-demo-演示
官方-demo-github
laravel-admin-插件库

在管理员字段中如何添加电话和邮箱字段
资源控制器-覆盖默认路由
Grid中导出表格含有中文字符的CSV时出现乱码
laravel-admin表格数据导出乱码问题解决
laravel-debugbar-安装及配置
内置服务器监听端口
not configured, please add a disk config in config/filesystems.php

利用Laravel自带SMTP邮件组件实现发送邮件
laravel获取当前的url以及当前的基础域名方法汇总
EloquentORM关联关系

laravel-admin CURD

laravel-admin 实现文章列表、添加、编辑、删除、分页、检索 laravel-admin 基础增删改查

效果图

laravel-admin curd
laravel-admin 入库

涉及文件

|--app
|--|--Admin
|--|--|--Controllers
|--|--|--|TestController.php #手动创建
|--|--|--routers.php
|--|--Models #手动创建
|--|--|--Movie.php #手动创建

TestController.php

<?php
namespace App\Admin\Controllers;
use App\Models\Movie;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class TestController extends AdminController
{
    protected $title = '测试';

    protected function grid()
    {
        $grid = new Grid(new Movie());
        $grid->id('ID')->sortable();
        $grid->title('标题')->editable();
        $grid->director()->editable();
        $grid->describe()->editable();
        $grid->created_at();
        $grid->updated_at();
        return $grid;
    }
    protected function form()
    {
        $form = new Form(new Movie());
        $form->display('id', 'ID');
        $form->text('title', '标题')->rules('required');
        $form->text('director')->rules('required');
        $form->text('describe')->rules('required');
        $form->display('created_at', 'Created At');
        $form->display('updated_at', 'Updated At');
        return $form;
    }
}

Movie.php

<?php
namespace App\Models;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Model;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class Movie extends Model implements Sortable
{
    use SortableTrait;

    protected $table = 'movies';

    public $sortable = [
        'order_column_name' => 'rate',
        'sort_when_creating' => true,
    ];

    public static function grid($callback)
    {
        return new Grid(new static, $callback);
    }
    public static function form($callback)
    {
        return new Form(new static, $callback);
    }
}

routers.php

<?php

use Illuminate\Routing\Router;

Admin::routes();

Route::group([
    'prefix'        => config('admin.route.prefix'),
    'namespace'     => config('admin.route.namespace'),
    'middleware'    => config('admin.route.middleware'),
], function (Router $router) {

    $router->get('/', 'HomeController@index')->name('admin.home');
    // CURD 路由
    $router->resources([
        'test'  => TestController::class,
    ]);
});

Tip: 查看composer.json如果下面包没有则需要安装

composer require "spatie/eloquent-sortable:^3.4"

composer require "spatie/laravel-backup:^5.0"

数据库表

CREATE TABLE `movies` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `director` int(10) unsigned NOT NULL,
  `describe` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `rate` tinyint unsigned NOT NULL,
  `released` enum('0', '1'),
  `release_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Tip: SQL执行报错 ERROR 1067 (42000): Invalid default value for ‘release_at’

处理 === 去掉 sql_mode 中的 values: NO_ZERO_IN_DATE,NO_ZERO_DATE 即可

进入mysql 执行命令 show variables like 'sql_mode';

然后复制值 set session
sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
再重新设置值(Tip: 不要直接复制执行)

菜单添加

laravel-admin 菜单

相关资料

参考-ArticleController-demo
ERROR 1067-mysql报错

laravel-admin部署

laravel-admin 部署安装

环境说明

  • ubuntu
  • laradock
  • php7.2
  • mysql-5.7
  • laravel-5.5

部署步骤

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ 阿里composer镜像服务

安装laravelcomposer create-project --prefer-dist laravel/laravel blog "5.5.*"

资源发布 php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider"

安装 php artisan admin:install Tip: 先配置.env数据库信息

启动服务后,在浏览器打开 http://localhost/admin/ ,使用用户名 admin 和密码 admin登录. Tip: 配置vhost

相关资料

laravel-admin 官方安装文档

mojito部署

mojito laravel+elm 前后分离后台

部署安装文档中题的部署出现的问题

环境-mac laradock php-7.2 mysql-5.7 部署mojito1.1.*

ERROR in multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
Module not found: Error: Can't resolve '/var/www/mojito/resources/assets/js/app.js' in '/var/www/mojito'
 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss /js/app[0]

原文档内容

Mix 引入 admin.js

mix.js(‘resources/assets/js/app.js’, ‘public/js’)
.sass(‘resources/assets/sass/app.scss’, ‘public/css’)
//.js(‘resources/js/admin.js’, ‘public/js’) laravel5.7+
.js(‘resources/assets/js/admin.js’, ‘public/js’)

实验后

将下面代码替换文件原来的内容-(文件在跟目录) webpack.mix.js

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .js('resources/js/admin.js', 'public/js');

由于是部署在laradock中所以不能直接访问localhost

nginx-vhost

server {

    listen 80;
    listen [::]:80;

    # For https
    # listen 443 ssl;
    # listen [::]:443 ssl ipv6only=on;
    # ssl_certificate /etc/nginx/ssl/default.crt;
    # ssl_certificate_key /etc/nginx/ssl/default.key;

    server_name mojito.test;
    root /var/www/mojito/public;
    index index.php index.html index.htm;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_pass php-upstream;
        fastcgi_index index.php;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #fixes timeouts
        fastcgi_read_timeout 600;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt/;
        log_not_found off;
    }

    error_log /var/log/nginx/laravel_error.log;
    access_log /var/log/nginx/laravel_access.log;
}

hosts文件末尾追加

127.0.0.1   mojito.test

浏览器打开:http://mojito.test/mojito#/admin/login

相关资料

mojito-文档
mojito-github

laravel-跨域解决

Laravel API接口跨域访问 “Access-Control-Allow-Origin”

step1-创建中间件

创建文件app/Http/Middleware/CORS.php, 将下面代码复制到文件中.

<?php
namespace App\Http\Middleware;
use Closure;

class CORS
{
    public function handle($request, Closure $next)
    {
        return $next($request)->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization,X-Requested-With');
    }
}

step2-注册中间件路由

打开文件: \app\Http\Kernel.php, 找到 protected $middleware 然后增加\App\Http\Middleware\CORS::class,

protected $middleware = [
    ...
    \App\Http\Middleware\CORS::class, //跨域访问中间件
    ...
];

相关资料

Laravel API接口跨域访问

laravel 插入数据报错 doesn’t have a default value 

laravel-mysql-默认为严格的验证方式

Tip: 在Config/database.php中设置’strict’ => false

'mysql' => [
    'driver' => 'mysql',
    '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' => '',
    'strict' => fasle,
    'engine' => null,
],

相关资料

laravel中mysql默认使用了严格的验证方式

laravel文件上传

if ($request->isMethod('post')) {

            $file = $request->file('picture');

            // 文件是否上传成功
            if ($file->isValid()) {

                // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                $type = $file->getClientMimeType();     // image/jpeg

                // 上传文件
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间(目录)
                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                var_dump($bool);

            }

}

相关资料

laravel-文件上传

动手做接口前应该注意哪些问题?

  • 接口认证
  • 接口参数格式字段
  • 接口版本 保留几个版本 什么情况下需要强制升级
  • 自动化测试问题
  • 模块化分
  • 接口统计问题
  • 隐式用户与显式用户
  • 对于线上的 API 必须保证所有接口正常且关闭所有的错误信息 => error_reporting(0),在输出JSON 时,不能有任何其它输出,否则,客户端将解析数据失败,app直接闪退

相关资料

API接口开发过程中的注意事项

APP接口版本兼容的问题
APP版本强制升级
APP升级二三事:APP升级场景及功能设计总结
App后端API设计版本问题

PHP / Laravel API 开发推荐阅读清单 有写关于Laravel的资料比较久