Laravel批量删除

有时,客户端会提交过来一些ID,需要删除这些ID对应的数据,代码如下:

public function destroy(Request $request): JsonResponse
{
    $customs = $request->collect();
    Custom::whereIn('id', $customs->pluck('id'))->delete();

    return response()->json(['code'=>0, 'msg'=>'删除成功!']);
}

C++14关联容器set自定义排序函数报错

十年前写的一个C++项目编译报错:“bool compatetor_asc::operator ()(const std::wstring &,const std::wstring &)”: 不能将“this”指针从“const compatetor_asc”转换为“compatetor_asc &”。

对应的代码如下 :

class compatetor_asc
{
public:
    bool operator()(const std::wstring& lhs, const std::wstring& rhs) 
    {
        return lhs < rhs ;
    }
};

这段代码重载了函数调用操作符(),可以让该类的对象能够像函数一样使用。调用的代码std::set<std::wstring, compatetor_asc> m_OriginalAsc;。

当时这个C++项目是用VS2008开发的,C++标准是C++03,现在用VS2022来编译,用的C++标准是C++14。

简单解了一下,原来从C++11开始,标准库排序谓词函数就要求必须是const成员函数了,那么只要把operator()函数改为const成员函数即可。

bool operator()(const std::wstring& lhs, const std::wstring& rhs) const
{
    return lhs < rhs ;
}

修改后再次编译,问题解决。

后记:

已经有近十年没有写过C++项目了,最初学习C++用的是VC++6.0,标准是C++98,到后来有了C++03,现如今已经到了C++23了,二十年如一梦。

Laravel打印Eloquent生成的完整SQL

开发调试中,经常需要查看Eloquent生成的SQL语句,以便排查错误,具体做法如下:

引入:use Illuminate\Support\Facades\DB;

DB::connection()->enableQueryLog(); // 开启QueryLog

$workLogs = WorkLog::where(function ($query) use ($request) {
    if ($request->has('keyword')) {
        $query->where('content', 'like', "%{$request->keyword}%");
    }
    if ($request->has('department_id')) {
        $query->with('user', function($userQuery) {
            $userQuery->where('department_id', $request->department_id);
        });
    }
})->orderByDesc('created_at')->paginate();

dd(DB::getQueryLog());

Laravel中ajax请求与csrf-token

Laravel中为了安全,请求会附带上csrf-token,当然也可以暴力的在VerifyCsrfToken中间件中排除项填写“*”以全局禁用,不过为了安全,这不是推荐的做法。

对于ajax请求,当然也需要带上csrf-token,具体做法如下:

在header中添加:

<meta name="csrf-token" content="{{ csrf_token() }}" />

然后在JS中添加:

<script type="text/javascript">
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
</script>

然后ajax就可以无感使用csrf了。

Laravel命名规范

路由:

URL:对于超过一个单词的情况,使用破折号-

路由名称:

超过一个单词,使用下划线:

例如:

Route::post('product-details/fetch', 'ProductDetailController@fetch')->name('product_details.fetch');

对于视图文件夹,超过连个单词,可以使用下划线:

views/master_products/xxx.blade.php

对于视图文件,使用短横线-,例如

show-filtered.blade.php

合起来就是:

views/master_products/show-filtered.blade.php

更多规范可以参考:https://github.com/alexeymezenin/laravel-best-practices/blob/master/chinese.md

后记:

不管是否采用该规范,最重要的是风格统一,没有什么标准,自己写的舒服,风格统一就是标准!

Debian12安装PHP7.4

请注意:PHP7.4已经于2022年11月28日停止维护。

安装sury源:

#!/bin/sh
# To add this repository please do:
if [ "$(whoami)" != "root" ]; then
    SUDO=sudo
fi
${SUDO} apt-get update
${SUDO} apt-get -y install lsb-release ca-certificates curl
${SUDO} curl -sSLo /tmp/debsuryorg-archive-keyring.deb https://packages.sury.org/debsuryorg-archive-keyring.deb
${SUDO} dpkg -i /tmp/debsuryorg-archive-keyring.deb
${SUDO} sh -c 'echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
${SUDO} apt-get update

安装PHP7.4:

apt install -y php7.4-fpm php7.4-mysql php7.4-mbstring php7.4-curl php7.4-xml php7.4-imagick php7.4-zip php7.4-gd php7.4-intl php7.4-bcmath

Laravel中Auth::viaRemember() 功能解读

Auth::viaRemember() 这个函数只有在第一次登录过期后,当系统通过remember进行认证时,才返回true。

第一次见这个函数时,试了下,始终返回false,后来经过搜索,结合自己的想法,觉得应该就是这样的。过了一晚,第二天早上再试,这个函数就返回true了。

wordpress获取某个分类下文章的标签列表

WordPress 提供了函数来获取某个分类下文章的标签列表。可以使用 get_terms() 和 wp_get_post_tags() 函数来实现该功能。

// 获取特定分类下的标签
$category_id = 1; // 替换为你想要查询的分类ID
$tags = get_terms( array(
    'taxonomy' => 'post_tag', // 标签的 taxonomy 名称
    'object_ids' => get_posts( array(
        'posts_per_page' => -1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'category' => $category_id, // 指定分类ID
        'fields' => 'ids',
    ) ),
    'hide_empty' => false, // 设置为 false 以包括没有文章的标签
) );

// 输出标签
if ( ! is_wp_error( $tags ) && ! empty( $tags ) ) {
    foreach ( $tags as $tag ) {
        echo $tag->name . '<br>';
    }
} else {
    echo '没有标签';
}

Laravel 9 使用 Vite 整合 Vue 3

Laravel 作为一个全栈开发框架,天然支持把前后端集成在一起开发,避免了前后端两个项目在不同开发工具中进行切换,节省很多时间,开发体验更好,真是自由全栈开发者的一大利器。

在本文中,我们将使用 vite 在 laravel 9 中安装 vue 3。

创建 Laravel 项目

composer create-project laravel/laravel laravel-vite-vue

安装 vue 3 和 vue-loader

npm install vue@next vue-loader@next

安装 plugin-vue

npm i @vitejs/plugin-vue

安装其它依赖

npm install

编辑 vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [
        vue(),
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
        ]),
    ],
});

修改 resources/js/app.js

import './bootstrap';

import { createApp } from 'vue';

import app from './Page/app.vue'

createApp(app).mount("#app")

在 resources/Page 文件夹下添加 app.vue,内容如下

<template>
    <h1>
        Laravel 9 vite with vue 3
    </h1>
</template>

编辑 resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 9 with vue 3 vite</title>

    </head>
    <body>
        <div id="app"></div>
        @vite('resources/js/app.js')
    </body>
</html>

执行 npm run dev 和 php artisan serve 。

最后打开 https://notes.wujie.me:8000 就可以看效果了。

对于高版本Laravel,应该大同小异,以此为参考进行。

wordpress获取某一篇文章所在分类的子分类

要获取某篇文章所在分类的子分类,可以首先通过 get_the_category() 获取文章的分类 ID,然后再根据该分类的 ID 获取子分类。

以下是一个示例代码:

$post_id = 123; // 文章的 ID
$categories = get_the_category($post_id);

if (!empty($categories)) {
    $parent_category_id = $categories[0]->term_id; // 获取文章的第一个分类的 ID
    $taxonomy = 'category'; // 分类的 taxonomy,通常是 'category'

    $args = array(
        'taxonomy'     => $taxonomy,
        'parent'        => $parent_category_id,
        'hide_empty'    => false, // 是否排除没有文章的分类
    );

    $subcategories = get_terms($args);

    if (!empty($subcategories) && !is_wp_error($subcategories)) {
        foreach ($subcategories as $subcategory) {
            echo '子分类名称: ' . $subcategory->name . '<br>';
            echo '子分类链接: ' . get_term_link($subcategory) . '<br>';
        }
    } else {
        echo '没有找到子分类。';
    }
} else {
    echo '文章没有分类。';
}

说明:

  • get_the_category($post_id) 获取文章所属的分类。如果文章属于多个分类,它会返回一个分类数组,这里我们使用了第一个分类的 ID($categories[0]->term_id)。
  • 然后,使用该分类 ID 查询其子分类,get_terms() 返回该分类下的子分类列表。

这段代码假设文章有至少一个分类,并且你希望基于第一个分类获取子分类。如果文章有多个分类,你可以根据需求修改代码,选择不同的分类来获取子分类。