diff --git a/404.html b/404.html index 304c82692..0009265a6 100644 --- a/404.html +++ b/404.html @@ -15,7 +15,7 @@
Skip to content

404

PAGE NOT FOUND

But if you don't change your direction, and if you keep looking, you may end up where you are heading.
- + \ No newline at end of file diff --git a/README.html b/README.html index fa6b853c0..52b187ddd 100644 --- a/README.html +++ b/README.html @@ -11,13 +11,13 @@ - + -
Skip to content

Laravel 学习记录

开发

bash
# install in your project
+    
Skip to content

Laravel 学习记录

开发

bash
# install in your project
 yarn
 
 # start writing
@@ -46,7 +46,7 @@
 
 # build to static files
 npx prod
- + \ No newline at end of file diff --git a/assets/README.md.3e1a4b98.lean.js b/assets/README.md.3e1a4b98.lean.js deleted file mode 100644 index aee4e8265..000000000 --- a/assets/README.md.3e1a4b98.lean.js +++ /dev/null @@ -1 +0,0 @@ -import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const b=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),p={name:"README.md"},e=l("",3),o=[e];function t(c,r,i,d,y,h){return a(),n("div",null,o)}const u=s(p,[["render",t]]);export{b as __pageData,u as default}; diff --git a/assets/README.md.3e1a4b98.js b/assets/README.md.64131247.js similarity index 90% rename from assets/README.md.3e1a4b98.js rename to assets/README.md.64131247.js index a59e5e52b..4eac2024c 100644 --- a/assets/README.md.3e1a4b98.js +++ b/assets/README.md.64131247.js @@ -1,4 +1,4 @@ -import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const b=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),p={name:"README.md"},e=l(`

Laravel 学习记录

开发

bash
# install in your project
+import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),p={name:"README.md"},e=l(`

Laravel 学习记录

开发

bash
# install in your project
 yarn
 
 # start writing
@@ -26,4 +26,4 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const b=
 npx watch
 
 # build to static files
-npx prod
`,3),o=[e];function t(c,r,i,d,y,h){return a(),n("div",null,o)}const u=s(p,[["render",t]]);export{b as __pageData,u as default}; +npx prod
`,3),o=[e];function t(c,i,r,d,y,h){return a(),n("div",null,o)}const b=s(p,[["render",t]]);export{u as __pageData,b as default}; diff --git a/assets/README.md.64131247.lean.js b/assets/README.md.64131247.lean.js new file mode 100644 index 000000000..f7a898c37 --- /dev/null +++ b/assets/README.md.64131247.lean.js @@ -0,0 +1 @@ +import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),p={name:"README.md"},e=l("",3),o=[e];function t(c,i,r,d,y,h){return a(),n("div",null,o)}const b=s(p,[["render",t]]);export{u as __pageData,b as default}; diff --git a/assets/collections_all.md.866e26e5.js b/assets/collections_all.md.80ab9cd4.js similarity index 96% rename from assets/collections_all.md.866e26e5.js rename to assets/collections_all.md.80ab9cd4.js index 40cc3d0e6..9cd39865c 100644 --- a/assets/collections_all.md.866e26e5.js +++ b/assets/collections_all.md.80ab9cd4.js @@ -4,7 +4,7 @@ import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C= collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]
collect([1, 2, 3, 4])->all(); // [1, 2, 3, 4]
 
 // 上面 \`all\` 方法的调用类似于 \`toArray\` 方法
-collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]

与 toArray 的区别

all 方法与 toArray 方法的区别在于嵌套集合在调用方法后生成的结果不同。

php
// 使用 all 方法只会将集合中首层的元素格式化为数组
+collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]

与 toArray 的区别

all 方法与 toArray 方法的区别在于嵌套集合在调用方法后生成的结果不同。

php
// 使用 all 方法只会将集合中首层的元素格式化为数组
 collect([collect([1, 2, 3, 4]), collect([1, 2, 3, 4])])->all();
 
 /**
@@ -44,4 +44,4 @@ import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C=
  [1, 2, 3, 4],
  [1, 2, 3, 4],
 ]
-*/

关联方法

`,8),e=[o];function t(c,r,y,i,E,F){return a(),l("div",null,e)}const B=s(p,[["render",t]]);export{C as __pageData,B as default}; +*/

关联方法

`,8),t=[o];function e(c,r,y,i,E,F){return a(),l("div",null,t)}const B=s(p,[["render",e]]);export{C as __pageData,B as default}; diff --git a/assets/collections_all.md.866e26e5.lean.js b/assets/collections_all.md.80ab9cd4.lean.js similarity index 69% rename from assets/collections_all.md.866e26e5.lean.js rename to assets/collections_all.md.80ab9cd4.lean.js index 26563a7c4..f594413e6 100644 --- a/assets/collections_all.md.866e26e5.lean.js +++ b/assets/collections_all.md.80ab9cd4.lean.js @@ -1 +1 @@ -import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"all","description":"","frontmatter":{},"headers":[],"relativePath":"collections/all.md","filePath":"collections/all.md","lastUpdated":1695352325000}'),p={name:"collections/all.md"},o=n("",8),e=[o];function t(c,r,y,i,E,F){return a(),l("div",null,e)}const B=s(p,[["render",t]]);export{C as __pageData,B as default}; +import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"all","description":"","frontmatter":{},"headers":[],"relativePath":"collections/all.md","filePath":"collections/all.md","lastUpdated":1695352325000}'),p={name:"collections/all.md"},o=n("",8),t=[o];function e(c,r,y,i,E,F){return a(),l("div",null,t)}const B=s(p,[["render",e]]);export{C as __pageData,B as default}; diff --git a/assets/collections_avg.md.7fcecbb3.js b/assets/collections_avg.md.cb046321.js similarity index 98% rename from assets/collections_avg.md.7fcecbb3.js rename to assets/collections_avg.md.cb046321.js index a4c5993b1..f876d5d50 100644 --- a/assets/collections_avg.md.7fcecbb3.js +++ b/assets/collections_avg.md.cb046321.js @@ -1,4 +1,4 @@ -import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"avg","description":"","frontmatter":{},"headers":[],"relativePath":"collections/avg.md","filePath":"collections/avg.md","lastUpdated":1695352397000}'),p={name:"collections/avg.md"},o=l(`

avg

返回数组中给定键的值的平均值

一些示例

php
// 获取一维数组
+import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"avg","description":"","frontmatter":{},"headers":[],"relativePath":"collections/avg.md","filePath":"collections/avg.md","lastUpdated":1695352397000}'),p={name:"collections/avg.md"},o=l(`

avg

返回数组中给定键的值的平均值

一些示例

php
// 获取一维数组
 collect([10, 20, 30])->average(); // 20
 
 // 获取二维数组的平均值
diff --git a/assets/collections_avg.md.7fcecbb3.lean.js b/assets/collections_avg.md.cb046321.lean.js
similarity index 100%
rename from assets/collections_avg.md.7fcecbb3.lean.js
rename to assets/collections_avg.md.cb046321.lean.js
diff --git a/assets/collections_chunk.md.e82aef25.js b/assets/collections_chunk.md.1ec3da6e.js
similarity index 96%
rename from assets/collections_chunk.md.e82aef25.js
rename to assets/collections_chunk.md.1ec3da6e.js
index d373a3b98..1f5bd2787 100644
--- a/assets/collections_chunk.md.e82aef25.js
+++ b/assets/collections_chunk.md.1ec3da6e.js
@@ -1,4 +1,4 @@
-import{_ as s,o as l,c as a,Q as n}from"./chunks/framework.16715cb7.js";const B=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),p={name:"collections/chunk.md"},o=n(`

chuck

将集合拆分为多个指定大小的集合组。

一些示例

php
collect([1, 2, 3, 4, 5, 6, 7, 8])->chunk(4); 
+import{_ as s,o as l,c as a,Q as n}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),p={name:"collections/chunk.md"},o=n(`

chuck

将集合拆分为多个指定大小的集合组。

一些示例

php
collect([1, 2, 3, 4, 5, 6, 7, 8])->chunk(4); 
 /**
 => Illuminate\\Support\\Collection {#1089
      all: [
@@ -52,4 +52,4 @@ import{_ as s,o as l,c as a,Q as n}from"./chunks/framework.16715cb7.js";const B=
        },
      ],
    }
-*/

相关方法

`,6),t=[o];function e(c,i,r,y,E,u){return l(),a("div",null,t)}const h=s(p,[["render",e]]);export{B as __pageData,h as default}; +*/

相关方法

`,6),t=[o];function e(c,i,r,y,E,u){return l(),a("div",null,t)}const B=s(p,[["render",e]]);export{h as __pageData,B as default}; diff --git a/assets/collections_chunk.md.e82aef25.lean.js b/assets/collections_chunk.md.1ec3da6e.lean.js similarity index 60% rename from assets/collections_chunk.md.e82aef25.lean.js rename to assets/collections_chunk.md.1ec3da6e.lean.js index 410fbf0e8..dbf2feab9 100644 --- a/assets/collections_chunk.md.e82aef25.lean.js +++ b/assets/collections_chunk.md.1ec3da6e.lean.js @@ -1 +1 @@ -import{_ as s,o as l,c as a,Q as n}from"./chunks/framework.16715cb7.js";const B=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),p={name:"collections/chunk.md"},o=n("",6),t=[o];function e(c,i,r,y,E,u){return l(),a("div",null,t)}const h=s(p,[["render",e]]);export{B as __pageData,h as default}; +import{_ as s,o as l,c as a,Q as n}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),p={name:"collections/chunk.md"},o=n("",6),t=[o];function e(c,i,r,y,E,u){return l(),a("div",null,t)}const B=s(p,[["render",e]]);export{h as __pageData,B as default}; diff --git a/assets/collections_collapse.md.4af04df9.js b/assets/collections_collapse.md.57414593.js similarity index 97% rename from assets/collections_collapse.md.4af04df9.js rename to assets/collections_collapse.md.57414593.js index 668ce3017..05cd65396 100644 --- a/assets/collections_collapse.md.4af04df9.js +++ b/assets/collections_collapse.md.57414593.js @@ -1,4 +1,4 @@ -import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"collapse","description":"","frontmatter":{},"headers":[],"relativePath":"collections/collapse.md","filePath":"collections/collapse.md","lastUpdated":1695352109000}'),o={name:"collections/collapse.md"},p=n(`

collapse

将数组集合折叠成单个集合。

相关示例

php
$collections = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
+import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const C=JSON.parse('{"title":"collapse","description":"","frontmatter":{},"headers":[],"relativePath":"collections/collapse.md","filePath":"collections/collapse.md","lastUpdated":1695352109000}'),o={name:"collections/collapse.md"},p=n(`

collapse

将数组集合折叠成单个集合。

相关示例

php
$collections = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
 
 collect($collections)->collapse(); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
diff --git a/assets/collections_collapse.md.4af04df9.lean.js b/assets/collections_collapse.md.57414593.lean.js
similarity index 100%
rename from assets/collections_collapse.md.4af04df9.lean.js
rename to assets/collections_collapse.md.57414593.lean.js
diff --git a/assets/collections_contains.md.29d5ded9.js b/assets/collections_contains.md.5f9e2e6d.js
similarity index 96%
rename from assets/collections_contains.md.29d5ded9.js
rename to assets/collections_contains.md.5f9e2e6d.js
index 5998af40a..7407609a7 100644
--- a/assets/collections_contains.md.29d5ded9.js
+++ b/assets/collections_contains.md.5f9e2e6d.js
@@ -1,4 +1,4 @@
-import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"contains","description":"","frontmatter":{},"headers":[],"relativePath":"collections/contains.md","filePath":"collections/contains.md","lastUpdated":1696669800000}'),o={name:"collections/contains.md"},p=l(`

contains

判断集合是否包含给定的项目,返回最后匹配的布尔值。

php
collect(['value'])->contains('value1'); // false
+import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"contains","description":"","frontmatter":{},"headers":[],"relativePath":"collections/contains.md","filePath":"collections/contains.md","lastUpdated":1696669800000}'),o={name:"collections/contains.md"},p=l(`

contains

判断集合是否包含给定的项目,返回最后匹配的布尔值。

php
collect(['value'])->contains('value1'); // false
 collect(['value'])->contains('value'); // true
 collect(['key' => 'value'])->contains('value'); // true
collect(['value'])->contains('value1'); // false
 collect(['value'])->contains('value'); // true
@@ -22,4 +22,4 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
 $collection->contains(fn ($value, $key) => $value > 5); // false
$collection = collect([1, 2, 3, 4, 5]);
 
 $collection->contains(fn ($value, $key) => $value > 4); // true
-$collection->contains(fn ($value, $key) => $value > 5); // false

相关方法

`,5),e=[p];function t(c,r,y,E,i,F){return a(),n("div",null,e)}const h=s(o,[["render",t]]);export{u as __pageData,h as default}; +$collection->contains(fn ($value, $key) => $value > 5); // false

相关方法

`,5),e=[p];function t(c,r,y,E,i,F){return a(),n("div",null,e)}const g=s(o,[["render",t]]);export{u as __pageData,g as default}; diff --git a/assets/collections_contains.md.29d5ded9.lean.js b/assets/collections_contains.md.5f9e2e6d.lean.js similarity index 73% rename from assets/collections_contains.md.29d5ded9.lean.js rename to assets/collections_contains.md.5f9e2e6d.lean.js index 605a152d6..85094832d 100644 --- a/assets/collections_contains.md.29d5ded9.lean.js +++ b/assets/collections_contains.md.5f9e2e6d.lean.js @@ -1 +1 @@ -import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"contains","description":"","frontmatter":{},"headers":[],"relativePath":"collections/contains.md","filePath":"collections/contains.md","lastUpdated":1696669800000}'),o={name:"collections/contains.md"},p=l("",5),e=[p];function t(c,r,y,E,i,F){return a(),n("div",null,e)}const h=s(o,[["render",t]]);export{u as __pageData,h as default}; +import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"contains","description":"","frontmatter":{},"headers":[],"relativePath":"collections/contains.md","filePath":"collections/contains.md","lastUpdated":1696669800000}'),o={name:"collections/contains.md"},p=l("",5),e=[p];function t(c,r,y,E,i,F){return a(),n("div",null,e)}const g=s(o,[["render",t]]);export{u as __pageData,g as default}; diff --git a/assets/collections_countBy.md.f3b908c9.js b/assets/collections_countBy.md.09a23ae5.js similarity index 96% rename from assets/collections_countBy.md.f3b908c9.js rename to assets/collections_countBy.md.09a23ae5.js index 87abb8996..3d0f43ac9 100644 --- a/assets/collections_countBy.md.f3b908c9.js +++ b/assets/collections_countBy.md.09a23ae5.js @@ -1,4 +1,4 @@ -import{_ as s,o as a,c as o,Q as l}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"countBy","description":"","frontmatter":{},"headers":[],"relativePath":"collections/countBy.md","filePath":"collections/countBy.md","lastUpdated":1695368331000}'),n={name:"collections/countBy.md"},p=l(`

countBy

计算集合中值的出现次数,默认情况下,该方法计算每个元素的出现次数,允许计算集合中某些"类型"的元素。

php
collect([1, 2, 2, 2, 3])->countBy();
+import{_ as s,o as a,c as o,Q as l}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"countBy","description":"","frontmatter":{},"headers":[],"relativePath":"collections/countBy.md","filePath":"collections/countBy.md","lastUpdated":1695368331000}'),n={name:"collections/countBy.md"},p=l(`

countBy

计算集合中值的出现次数,默认情况下,该方法计算每个元素的出现次数,允许计算集合中某些"类型"的元素。

php
collect([1, 2, 2, 2, 3])->countBy();
 
 // [1 => 1, 2 => 3, 3 => 1]
collect([1, 2, 2, 2, 3])->countBy();
 
diff --git a/assets/collections_countBy.md.f3b908c9.lean.js b/assets/collections_countBy.md.09a23ae5.lean.js
similarity index 100%
rename from assets/collections_countBy.md.f3b908c9.lean.js
rename to assets/collections_countBy.md.09a23ae5.lean.js
diff --git a/assets/collections_examples_format-github-events-score.md.48994faf.js b/assets/collections_examples_format-github-events-score.md.beda6110.js
similarity index 99%
rename from assets/collections_examples_format-github-events-score.md.48994faf.js
rename to assets/collections_examples_format-github-events-score.md.beda6110.js
index 6948af824..a66059dc4 100644
--- a/assets/collections_examples_format-github-events-score.md.48994faf.js
+++ b/assets/collections_examples_format-github-events-score.md.beda6110.js
@@ -50,7 +50,7 @@ import{_ as s,o as n,c as a,Q as p}from"./chunks/framework.16715cb7.js";const v=
   }
 }
 
-dd($score); // 输出 134

使用 pluckmapsum 方法

php
$events = collect(
+dd($score); // 输出 134

使用 pluckmapsum 方法

php
$events = collect(
   Http::get('https://api.github.com/users/curder/events')->json()
 );
 
@@ -154,7 +154,7 @@ import{_ as s,o as n,c as a,Q as p}from"./chunks/framework.16715cb7.js";const v=
       'IssueCommentEvent' => 2,
     ])->get($eventType, 1); // 如果不存在则默认等于1
   })
-  ->sum();

封装 GitHubScore 类

php
$events = collect(
+  ->sum();

封装 GitHubScore 类

php
$events = collect(
     Http::get('https://api.github.com/users/curder/events')->json()
 );
 
diff --git a/assets/collections_examples_format-github-events-score.md.48994faf.lean.js b/assets/collections_examples_format-github-events-score.md.beda6110.lean.js
similarity index 100%
rename from assets/collections_examples_format-github-events-score.md.48994faf.lean.js
rename to assets/collections_examples_format-github-events-score.md.beda6110.lean.js
diff --git a/assets/collections_examples_order-info-summary.md.d3788c86.js b/assets/collections_examples_order-info-summary.md.459198e3.js
similarity index 98%
rename from assets/collections_examples_order-info-summary.md.d3788c86.js
rename to assets/collections_examples_order-info-summary.md.459198e3.js
index 6617acd69..94911c2a2 100644
--- a/assets/collections_examples_order-info-summary.md.d3788c86.js
+++ b/assets/collections_examples_order-info-summary.md.459198e3.js
@@ -112,7 +112,7 @@ import{_ as s,o as n,c as a,Q as p}from"./chunks/framework.16715cb7.js";const g=
         'qty' => 3,
         'customer_name'=>'Mandy',
     ],
-];
php
collect($orders)->groupBy('date');
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
+];
php
collect($orders)->groupBy('date');
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
 );
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
diff --git a/assets/collections_examples_order-info-summary.md.d3788c86.lean.js b/assets/collections_examples_order-info-summary.md.459198e3.lean.js
similarity index 100%
rename from assets/collections_examples_order-info-summary.md.d3788c86.lean.js
rename to assets/collections_examples_order-info-summary.md.459198e3.lean.js
diff --git a/assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.js b/assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.js
similarity index 97%
rename from assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.js
rename to assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.js
index 629d38db0..20edf0dbb 100644
--- a/assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.js
+++ b/assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.js
@@ -38,7 +38,7 @@ import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const F=
   'example' => 'example@example.com',
   'Lucy' => 'lucy@example.com',
   'Taylor'=> 'toylor@laravel.com'
-];

一些方法

php
collect($employees)->pluck('email', 'name'); 
+];

一些方法

php
collect($employees)->pluck('email', 'name'); 
 
 // ["example" => "example@exmaple.com", "Lucy" => "lucy@example.com", "Taylor" => "toylor@laravel.com"]
collect($employees)->pluck('email', 'name'); 
 
@@ -64,4 +64,4 @@ import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const F=
   return $emailLookup;
 }, []);
 
-// ["example" => "example@exmaple.com", "Lucy" => "lucy@example.com", "Taylor" => "toylor@laravel.com"]
`,7),e=[o];function t(c,r,y,E,i,u){return a(),l("div",null,e)}const d=s(p,[["render",t]]);export{F as __pageData,d as default}; +// ["example" => "example@exmaple.com", "Lucy" => "lucy@example.com", "Taylor" => "toylor@laravel.com"]
`,7),e=[o];function c(t,r,y,E,i,u){return a(),l("div",null,e)}const d=s(p,[["render",c]]);export{F as __pageData,d as default}; diff --git a/assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.lean.js b/assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.lean.js similarity index 78% rename from assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.lean.js rename to assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.lean.js index 460a60f95..f4de7b180 100644 --- a/assets/collections_examples_using-reduce-create-lookup-array.md.9a5539e4.lean.js +++ b/assets/collections_examples_using-reduce-create-lookup-array.md.303ebf67.lean.js @@ -1 +1 @@ -import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"通过原数组组装成其他数组格式","description":"","frontmatter":{},"headers":[],"relativePath":"collections/examples/using-reduce-create-lookup-array.md","filePath":"collections/examples/using-reduce-create-lookup-array.md","lastUpdated":1695889761000}'),p={name:"collections/examples/using-reduce-create-lookup-array.md"},o=n("",7),e=[o];function t(c,r,y,E,i,u){return a(),l("div",null,e)}const d=s(p,[["render",t]]);export{F as __pageData,d as default}; +import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"通过原数组组装成其他数组格式","description":"","frontmatter":{},"headers":[],"relativePath":"collections/examples/using-reduce-create-lookup-array.md","filePath":"collections/examples/using-reduce-create-lookup-array.md","lastUpdated":1695889761000}'),p={name:"collections/examples/using-reduce-create-lookup-array.md"},o=n("",7),e=[o];function c(t,r,y,E,i,u){return a(),l("div",null,e)}const d=s(p,[["render",c]]);export{F as __pageData,d as default}; diff --git a/assets/collections_first.md.909ffb1f.js b/assets/collections_first.md.db876798.js similarity index 96% rename from assets/collections_first.md.909ffb1f.js rename to assets/collections_first.md.db876798.js index 76f01b2da..a11f79872 100644 --- a/assets/collections_first.md.909ffb1f.js +++ b/assets/collections_first.md.db876798.js @@ -1,4 +1,4 @@ -import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"first","description":"","frontmatter":{},"headers":[],"relativePath":"collections/first.md","filePath":"collections/first.md","lastUpdated":1695377514000}'),p={name:"collections/first.md"},o=n(`

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
+import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const h=JSON.parse('{"title":"first","description":"","frontmatter":{},"headers":[],"relativePath":"collections/first.md","filePath":"collections/first.md","lastUpdated":1695377514000}'),p={name:"collections/first.md"},o=n(`

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
 collect([1, 2, 3, 4])->first(fn ($element) => $element > 3); // 4
// 从集合左往右遍历,满足条件元素被返回。
 collect([1, 2, 3, 4])->first(fn ($element) => $element > 3); // 4
php
// 当通过回调函数遍历集合没有满足条件的返回值时,默认值将会被返回
 collect([1, 2, 3, 4])->first(fn ($item) => $item < 1, 1000); // 1000
diff --git a/assets/collections_first.md.909ffb1f.lean.js b/assets/collections_first.md.db876798.lean.js
similarity index 100%
rename from assets/collections_first.md.909ffb1f.lean.js
rename to assets/collections_first.md.db876798.lean.js
diff --git a/assets/collections_firstWhere.md.5b378a38.js b/assets/collections_firstWhere.md.ca7b999c.js
similarity index 98%
rename from assets/collections_firstWhere.md.5b378a38.js
rename to assets/collections_firstWhere.md.ca7b999c.js
index 3d451554d..018413728 100644
--- a/assets/collections_firstWhere.md.5b378a38.js
+++ b/assets/collections_firstWhere.md.ca7b999c.js
@@ -1,4 +1,4 @@
-import{_ as s,o as a,c as p,Q as n}from"./chunks/framework.16715cb7.js";const d=JSON.parse('{"title":"firstWhere","description":"","frontmatter":{},"headers":[],"relativePath":"collections/firstWhere.md","filePath":"collections/firstWhere.md","lastUpdated":1695378156000}'),l={name:"collections/firstWhere.md"},o=n(`

firstWhere

返回给定键值对的第一个元素

php
collect([
+import{_ as s,o as a,c as p,Q as n}from"./chunks/framework.16715cb7.js";const d=JSON.parse('{"title":"firstWhere","description":"","frontmatter":{},"headers":[],"relativePath":"collections/firstWhere.md","filePath":"collections/firstWhere.md","lastUpdated":1695378156000}'),l={name:"collections/firstWhere.md"},o=n(`

firstWhere

返回给定键值对的第一个元素

php
collect([
   ['product' => 'apples', 'price' => 50],
   ['product' => 'pears', 'price' => 50],
   ['product' => 'banners', 'price' => 50],
diff --git a/assets/collections_firstWhere.md.5b378a38.lean.js b/assets/collections_firstWhere.md.ca7b999c.lean.js
similarity index 100%
rename from assets/collections_firstWhere.md.5b378a38.lean.js
rename to assets/collections_firstWhere.md.ca7b999c.lean.js
diff --git a/assets/collections_get.md.9e67411b.js b/assets/collections_get.md.c4c23075.js
similarity index 96%
rename from assets/collections_get.md.9e67411b.js
rename to assets/collections_get.md.c4c23075.js
index 5a4865c25..e43967041 100644
--- a/assets/collections_get.md.9e67411b.js
+++ b/assets/collections_get.md.c4c23075.js
@@ -1,4 +1,4 @@
-import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const g=JSON.parse('{"title":"get","description":"","frontmatter":{},"headers":[],"relativePath":"collections/get.md","filePath":"collections/get.md","lastUpdated":1695380014000}'),p={name:"collections/get.md"},o=n(`

get

获取一维数组给定键的集合项。如果该键不存在,则返回 null

php
collect(['name' => 'taylor', 'framework' => 'laravel'])
+import{_ as s,o as a,c as l,Q as n}from"./chunks/framework.16715cb7.js";const g=JSON.parse('{"title":"get","description":"","frontmatter":{},"headers":[],"relativePath":"collections/get.md","filePath":"collections/get.md","lastUpdated":1695380014000}'),p={name:"collections/get.md"},o=n(`

get

获取一维数组给定键的集合项。如果该键不存在,则返回 null

php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('name'); // "taylor"
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('name'); // "taylor"
php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('foo', 'bar'); // bar
collect(['name' => 'taylor', 'framework' => 'laravel'])
diff --git a/assets/collections_get.md.9e67411b.lean.js b/assets/collections_get.md.c4c23075.lean.js
similarity index 100%
rename from assets/collections_get.md.9e67411b.lean.js
rename to assets/collections_get.md.c4c23075.lean.js
diff --git a/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.dcb53a6b.js b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.97ae1369.js
similarity index 99%
rename from assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.dcb53a6b.js
rename to assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.97ae1369.js
index f8f603bc4..2d79229c0 100644
--- a/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.dcb53a6b.js
+++ b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.97ae1369.js
@@ -62,7 +62,7 @@ import{_ as s,o as n,c as a,Q as p}from"./chunks/framework.16715cb7.js";const C=
             'message' => 'Ticket purchased successfully.',
         ]);
     }
-}

此时可以将上面的代码使用自定义异常来编写,如下所示:

php
<?php
+}

此时可以将上面的代码使用自定义异常来编写,如下所示:

php
<?php
 
 namespace App\\Http\\Controllers;
 
diff --git a/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.dcb53a6b.lean.js b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.97ae1369.lean.js
similarity index 100%
rename from assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.dcb53a6b.lean.js
rename to assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.97ae1369.lean.js
diff --git a/assets/partials_blade.md.1678bdc7.js b/assets/partials_blade.md.c8fe88a9.js
similarity index 98%
rename from assets/partials_blade.md.1678bdc7.js
rename to assets/partials_blade.md.c8fe88a9.js
index 4d7d96f67..33cafc6fa 100644
--- a/assets/partials_blade.md.1678bdc7.js
+++ b/assets/partials_blade.md.c8fe88a9.js
@@ -22,7 +22,7 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
  // Load the view
 }
if (view()->exists('custom.page')) {
  // Load the view
-}

甚至可以加载一组视图,并且只会实际加载第一个存在的视图。

php
return view()->first(['custom.dashboard', 'dashboard'], $data);
return view()->first(['custom.dashboard', 'dashboard'], $data);

自定义错误页面

如果想为某些 HTTP 代码创建一个特定的错误页面,例如 500403 - 只需在 resources/views/errors/500.blade.phpresources/views/errors/403.blade.php 等中创建一个将此代码作为文件名的 blade 文件。

当出现该错误代码,它将自动加载。

官方文档 查看更多。

没有控制器的视图

如果希望路由仅显示某个视图,不用创建 Controller 方法,只需使用 Route::view() 函数。

php
Route::view('about', 'pages.about'); // 视图在 \`resources/pages/about.blade.php\`
Route::view('about', 'pages.about'); // 视图在 \`resources/pages/about.blade.php\`
php
// 1. 路由定义
+}

甚至可以加载一组视图,并且只会实际加载第一个存在的视图。

php
return view()->first(['custom.dashboard', 'dashboard'], $data);
return view()->first(['custom.dashboard', 'dashboard'], $data);

自定义错误页面

如果想为某些 HTTP 代码创建一个特定的错误页面,例如 500403 - 只需在 resources/views/errors/500.blade.phpresources/views/errors/403.blade.php 等中创建一个将此代码作为文件名的 blade 文件。

当出现该错误代码,它将自动加载。

官方文档 查看更多。

没有控制器的视图

如果希望路由仅显示某个视图,不用创建 Controller 方法,只需使用 Route::view() 函数。

php
Route::view('about', 'pages.about'); // 视图在 \`resources/pages/about.blade.php\`
Route::view('about', 'pages.about'); // 视图在 \`resources/pages/about.blade.php\`
php
// 1. 路由定义
 Route::get('about', [\\App\\Https\\Controllers\\PagesController::class, 'about']);
 
 // 2. 控制器
@@ -42,7 +42,7 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
     {
         return view('pages.about'); // 视图在 \`resources/pages/about.blade.php\`
     }
-}

@auth 模版指令

使用 @auth 指令代替 @if 语句来检查登录用户。

php
@if(auth()->user())
+}

@auth 模版指令

使用 @auth 指令代替 @if 语句来检查登录用户。

php
@if(auth()->user())
 // 用户已验证身份
 @endif
@if(auth()->user())
 // 用户已验证身份
@@ -110,11 +110,11 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
 
 @unlessenabled('regular-registration')
 // 该应用程序不接受常规注册
-@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

如果不确定模版文件是否真的存在,可以使用这些条件命令:

php
@includeIf('partials.header')
@includeIf('partials.header')
php
// 将仅为角色 ID 为 1 的用户加载对应模版 \`partials.header\`
+@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

如果不确定模版文件是否真的存在,可以使用这些条件命令:

php
@includeIf('partials.header')
@includeIf('partials.header')
php
// 将仅为角色 ID 为 1 的用户加载对应模版 \`partials.header\`
 @includeWhen(auth()->user()->role_id == 1, 'partials.header')
// 将仅为角色 ID 为 1 的用户加载对应模版 \`partials.header\`
 @includeWhen(auth()->user()->role_id == 1, 'partials.header')
php
// 尝试加载 \`adminlte.header\`,如果不存在,将加载 \`default.header\`
 @includeFirst('adminlte.header', 'default.header')
// 尝试加载 \`adminlte.header\`,如果不存在,将加载 \`default.header\`
-@includeFirst('adminlte.header', 'default.header')

使用 Blade-X 变量绑定来节省更多空间

php
@include("components.post", ["title" => $post->title])
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
+@includeFirst('adminlte.header', 'default.header')

使用 Blade-X 变量绑定来节省更多空间

php
@include("components.post", ["title" => $post->title])
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
 <x-post link="{{ $post->title }}"/>
 
 <!--使用 Blade-X 绑定变量-->
@@ -178,7 +178,7 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
 <x-navbar :title="$title"/>
 
 // 从 Laravel 9.32 开始可用
-<x-navbar :$title />

自动高亮导航链接

当精确的 URL 匹配时自动高亮显示导航链接,或者传递路径或路由名称,带有请求和 CSS 类的模版组件使得显示活动/非活动状态变得简单。

php
// 在模版中使用
+<x-navbar :$title />

自动高亮导航链接

当精确的 URL 匹配时自动高亮显示导航链接,或者传递路径或路由名称,带有请求和 CSS 类的模版组件使得显示活动/非活动状态变得简单。

php
// 在模版中使用
 <x-nav-link :href="route('projects.index')">Projects</x-nav-link>
 <x-nav-link :href="route('projects.index')" active="projects.*">Projects</x-nav-link>
 <x-nav-link :href="route('projects.index')" active="projects/*">Projects</x-nav-link>
@@ -258,7 +258,7 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
 </a>
// resources/views/components/nav-link.blade.php
 <a href="{{ $href }}" {{ $attributes->class($class) }}>
     {{ $slot }}
-</a>

@each 循环

php
// 1. 定义公共模版 resources/views/partials/item.blade.php
+</a>

@each 循环

php
// 1. 定义公共模版 resources/views/partials/item.blade.php
 <div>
     <p>Name: {{ $item->name }}
     <p>Price: {{ $item->price }}
@@ -290,7 +290,7 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
 </div>
 
 // 2. 使用
-@each('partials.item', $items, 'item')

整理模版的简单方法

php
// if/loop 组合
+@each('partials.item', $items, 'item')

整理模版的简单方法

php
// if/loop 组合
 @if ($orders->count())
     @foreach($orders as $order)
         <div>
@@ -342,11 +342,11 @@ import{_ as l,o as p,c as o,k as a,a as s,t as e,Q as n}from"./chunks/framework.
 
 @env(['staging', 'production'])
 // 测试环境或生产环境
-@endenv

@checked 指令

在 Laravel 9 中,可以使用 @checked 指令来选择 HTML 元素。

php
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
+@endenv

@checked 指令

在 Laravel 9 中,可以使用 @checked 指令来选择 HTML 元素。

php
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
 <input type="radio" name="active" value="0" @checked(!old('active', $user->active))/>
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
 <input type="radio" name="active" value="0" @checked(!old('active', $user->active))/>
php
<input type="radio" name="active" value="1" {{ old('active', $user->active) ? 'checked' : '' }}/>
 <input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>
<input type="radio" name="active" value="1" {{ old('active', $user->active) ? 'checked' : '' }}/>
-<input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>

@selected 指令

在 Laravel 9 中,可以使用 @selected 指令来选择 HTML 元素。

php
<select name="country">
+<input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>

@selected 指令

在 Laravel 9 中,可以使用 @selected 指令来选择 HTML 元素。

php
<select name="country">
     <option value="India" @selected(old('country') ?? $country == 'India')>India</option>
     <option value="Pakistan" @selected(old('country') ?? $country == 'Pakistan')>Pakistan</option>
 </select>
<select name="country">
diff --git a/assets/partials_blade.md.1678bdc7.lean.js b/assets/partials_blade.md.c8fe88a9.lean.js
similarity index 100%
rename from assets/partials_blade.md.1678bdc7.lean.js
rename to assets/partials_blade.md.c8fe88a9.lean.js
diff --git a/assets/partials_model-relations.md.79a609fd.js b/assets/partials_model-relations.md.50893065.js
similarity index 90%
rename from assets/partials_model-relations.md.79a609fd.js
rename to assets/partials_model-relations.md.50893065.js
index c8ae1471d..24397f09f 100644
--- a/assets/partials_model-relations.md.79a609fd.js
+++ b/assets/partials_model-relations.md.50893065.js
@@ -1,4 +1,4 @@
-import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"模型关系","description":"","frontmatter":{},"headers":[],"relativePath":"partials/model-relations.md","filePath":"partials/model-relations.md","lastUpdated":1700035971000}'),p={name:"partials/model-relations.md"},o=l(`

模型关系

关联关系的最新/旧项

从 Laravel 8.42 开始,在 Eloquent 模型中,可以定义一个关系,该关系将获取另一个关系的最新(或最旧)项目。

php
/**
+import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"模型关系","description":"","frontmatter":{},"headers":[],"relativePath":"partials/model-relations.md","filePath":"partials/model-relations.md","lastUpdated":1700036493000}'),p={name:"partials/model-relations.md"},o=l(`

模型关系

关联关系的最新/旧项

从 Laravel 8.42 开始,在 Eloquent 模型中,可以定义一个关系,该关系将获取另一个关系的最新(或最旧)项目。

php
/**
  * Get the user's latest order.
  */
 public function latestOrder()
@@ -128,4 +128,20 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const F=
 $users = Book::with('author.country:id,name')->get();
// Book -> belongsTo(Author::class)
 // Author -> belongsTo(Country::class)
 
-$users = Book::with('author.country:id,name')->get();
`,37),e=[o];function t(c,r,y,E,i,d){return a(),n("div",null,e)}const u=s(p,[["render",t]]);export{F as __pageData,u as default}; +$users = Book::with('author.country:id,name')->get();

更新父级

如果正在更新记录并想要更新 belongsTo 关系的 updated_at 列。

例如,添加新的帖子评论并希望 posts.updated_at 更新,只需要在 Comment 模型上定义 $touches 属性。

php
class Comment extends Model
+{
+    protected $touches = ['post'];
+
+    public function post()
+    {
+        return $this->belongsTo(Post::class); 
+    }
+}
class Comment extends Model
+{
+    protected $touches = ['post'];
+
+    public function post()
+    {
+        return $this->belongsTo(Post::class); 
+    }
+}
`,41),e=[o];function t(c,r,y,E,i,d){return a(),n("div",null,e)}const u=s(p,[["render",t]]);export{F as __pageData,u as default}; diff --git a/assets/partials_model-relations.md.79a609fd.lean.js b/assets/partials_model-relations.md.50893065.lean.js similarity index 71% rename from assets/partials_model-relations.md.79a609fd.lean.js rename to assets/partials_model-relations.md.50893065.lean.js index 124793ed7..2651173e5 100644 --- a/assets/partials_model-relations.md.79a609fd.lean.js +++ b/assets/partials_model-relations.md.50893065.lean.js @@ -1 +1 @@ -import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"模型关系","description":"","frontmatter":{},"headers":[],"relativePath":"partials/model-relations.md","filePath":"partials/model-relations.md","lastUpdated":1700035971000}'),p={name:"partials/model-relations.md"},o=l("",37),e=[o];function t(c,r,y,E,i,d){return a(),n("div",null,e)}const u=s(p,[["render",t]]);export{F as __pageData,u as default}; +import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const F=JSON.parse('{"title":"模型关系","description":"","frontmatter":{},"headers":[],"relativePath":"partials/model-relations.md","filePath":"partials/model-relations.md","lastUpdated":1700036493000}'),p={name:"partials/model-relations.md"},o=l("",41),e=[o];function t(c,r,y,E,i,d){return a(),n("div",null,e)}const u=s(p,[["render",t]]);export{F as __pageData,u as default}; diff --git a/assets/partials_model.md.a7a95a0e.js b/assets/partials_model.md.07e05036.js similarity index 99% rename from assets/partials_model.md.a7a95a0e.js rename to assets/partials_model.md.07e05036.js index 76747075d..6be91650d 100644 --- a/assets/partials_model.md.a7a95a0e.js +++ b/assets/partials_model.md.07e05036.js @@ -532,7 +532,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u= ]), 25);
return User::orderBy('name')->chunkMap(fn ($user) => [
     'id' => $user->id,
     'name' => $user->name,
-]), 25);

更新模型但不触发事件

有时需要在不发送任何事件的情况下更新模型。现在可以使用 updateQuietly() 方法来做到这一点,该方法在背后使用 saveQuietly() 方法。

php
$flight->updateQuietly(['departed' => false]);
$flight->updateQuietly(['departed' => false]);

定期清理过时记录中的模型

有了这个特性,Laravel会自动执行此操作,只需要在 Kernel 类中调整 model:prune 命令的频率即可。

php
use Illuminate\\Database\\Eloquent\\Model;
+]), 25);

更新模型但不触发事件

有时需要在不发送任何事件的情况下更新模型。现在可以使用 updateQuietly() 方法来做到这一点,该方法在背后使用 saveQuietly() 方法。

php
$flight->updateQuietly(['departed' => false]);
$flight->updateQuietly(['departed' => false]);

定期清理过时记录中的模型

有了这个特性,Laravel会自动执行此操作,只需要在 Kernel 类中调整 model:prune 命令的频率即可。

php
use Illuminate\\Database\\Eloquent\\Model;
 use Illuminate\\Database\\Eloquent\\Prunable;
 class Flight extends Model
 {
@@ -818,7 +818,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     return new Attribute(
         get: fn ($value) => strtoupper($value),
         set: fn ($value) => strtolower($value),
-}

自定义访问/修改器

如果要在许多模型中使用相同的访问器和修改器,可以使用自定义强制转换。

只需创建一个实现 CastsAttributes 接口的类,该类应该有两个方法,第一个是 get 指定如何从数据库检索模型,第二个是 set 指定如何将值存储在数据库中。

php
// 在模型类中使用强制转换
+}

自定义访问/修改器

如果要在许多模型中使用相同的访问器和修改器,可以使用自定义强制转换。

只需创建一个实现 CastsAttributes 接口的类,该类应该有两个方法,第一个是 get 指定如何从数据库检索模型,第二个是 set 指定如何将值存储在数据库中。

php
// 在模型类中使用强制转换
 
 class User extends Authenticatable
 {
@@ -882,7 +882,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
             // You can perform any action here
         });

直接将日期转换为人类可读的格式

可以使用 diffForHumans() 方法直接将 created_atupdated_at 日期转换为人类可读的格式。

例如:1分钟前、1个月前。Laravel 模型默认在 created_atupdated_at 字段上启用 Carbon 实例。

php
$post = Post::whereId($id)->first();
 $post->created_at->diffForHumans();
$post = Post::whereId($id)->first();
-$post->created_at->diffForHumans();

通过模型访问器进行排序

不是按数据库级别的访问器进行排序,而是按返回的 Collection 的访问器进行排序。

php
class User extends Model
+$post->created_at->diffForHumans();

通过模型访问器进行排序

不是按数据库级别的访问器进行排序,而是按返回的 Collection 的访问器进行排序。

php
class User extends Model
 {
     // ...
     protected $appends = ['full_name'];
@@ -956,7 +956,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     // 用户已存在并从数据库中获取
 }

数据库驱动程序 Laravel Scout

使用 Laravel9 及以上版本的 Laravel,可以将 Laravel Scout(搜索)与数据库驱动程序一起使用。

php
Company::search(request()->get('search'))->paginate(15);
Company::search(request()->get('search'))->paginate(15);

使用查询生成器上的 value 方法

当只需要查询单个列时,请使用查询生成器上的 value 方法来执行更有效的查询。

php
Statistic::where('user_id', 4)->first()->post_count; 
 Statistic::where('user_id', 4)->value('post_count');  
Statistic::where('user_id', 4)->first()->post_count; 
-Statistic::where('user_id', 4)->value('post_count');  

将数组传递给 where 方法

在使用模型查询数据时,允许将数组传递给 where 方法。

php
// You can pass an array
+Statistic::where('user_id', 4)->value('post_count');  

将数组传递给 where 方法

在使用模型查询数据时,允许将数组传递给 where 方法。

php
// You can pass an array
 JobPost::where([
     'company' => 'laravel',
     'job_type' => 'full time'
@@ -1106,7 +1106,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
 $category = Category::firstOrCreate(
     ['name' => $request->name],
     ['slug' => Str::slug($request->name)]
-);

保存模型及其所有关系

使用 push() 方法更新数据库中的主模型和相关模型。

php
$user = \\App\\Models\\User::first();
+);

保存模型及其所有关系

使用 push() 方法更新数据库中的主模型和相关模型。

php
$user = \\App\\Models\\User::first();
 $user->name = "John";
 $user->phone->number = '1234567890';
 $user->push(); // 更新数据库中的用户表中的记录和用户关联表中的电话号码记录
$user = \\App\\Models\\User::first();
diff --git a/assets/partials_model.md.a7a95a0e.lean.js b/assets/partials_model.md.07e05036.lean.js
similarity index 100%
rename from assets/partials_model.md.a7a95a0e.lean.js
rename to assets/partials_model.md.07e05036.lean.js
diff --git a/assets/partials_testing.md.e6422a98.js b/assets/partials_testing.md.b2dcd88d.js
similarity index 98%
rename from assets/partials_testing.md.e6422a98.js
rename to assets/partials_testing.md.b2dcd88d.js
index e87327c87..f6c2b18d5 100644
--- a/assets/partials_testing.md.e6422a98.js
+++ b/assets/partials_testing.md.b2dcd88d.js
@@ -26,7 +26,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
             $firstProduct->title,
             $secondProduct->title,
         ]);
-});

在这里,确保在页面上看到我们的产品名,如果从数据库加载产品并确保显示它们,这非常有用。

在这里你也可以更具体的添加对限定条件进行测试,比如当你只想展示 released 产品时。

php
it('lists released products', function () {
+});

在这里,确保在页面上看到我们的产品名,如果从数据库加载产品并确保显示它们,这非常有用。

在这里你也可以更具体的添加对限定条件进行测试,比如当你只想展示 released 产品时。

php
it('lists released products', function () {
     // Arrange
     $releasedProduct = Product::factory()
         ->released() 
@@ -68,7 +68,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     $this->get('/')
         ->assertOk()
         ->assertViewIs('index'); 
-});

可以更进一步并测试传递到视图的数据。

php
it('returns correct view', function() {
+});

可以更进一步并测试传递到视图的数据。

php
it('returns correct view', function() {
     // Act & Assert
     $this->get('/')
         ->assertOk()
@@ -142,7 +142,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
                 'description' => $anotherProduct->description,
             ],
         ]);
-});

可以在官网了解更多有关测试页面响应的信息。

数据库 Database

一般情况会将数据存储在数据库中,因此希望确保数据存储正确。

这就是 Laravel 可以通过一些断言助手来提供帮助。

php
// 该示例确保 post 请求成功并将数据正确的存储在数据库中。
+});

可以在官网了解更多有关测试页面响应的信息。

数据库 Database

一般情况会将数据存储在数据库中,因此希望确保数据存储正确。

这就是 Laravel 可以通过一些断言助手来提供帮助。

php
// 该示例确保 post 请求成功并将数据正确的存储在数据库中。
 it('stores a product', function () {
     // Act
     $this->actingAs(User::factory()->create())
@@ -194,7 +194,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
 
      // use directly assertModelMissing
      $this->assertModelMissing($task);
-});

可以在官网了解有关测试数据库的更多信息。

验证 Validation

Http请求

验证是许多应用程序的关键部分。在处理请求时候需要确保只能提交满足规则的数据。

默认情况下,Laravel 会将验证错误发送回用户,可以使用 assertInvalid 方法进行检查。

php
it('requires the title', function () {
+});

可以在官网了解有关测试数据库的更多信息。

验证 Validation

Http请求

验证是许多应用程序的关键部分。在处理请求时候需要确保只能提交满足规则的数据。

默认情况下,Laravel 会将验证错误发送回用户,可以使用 assertInvalid 方法进行检查。

php
it('requires the title', function () {
     // Act
     $this->actingAs(User::factory()->create())
         ->post('product', [
@@ -236,7 +236,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
 })->with([
     'title required' => [['description' => 'text'], ['title' => 'required']],
     'description required' => [['title' => 'Title'], ['description' => 'required']],
-]);

可以在官网了解更多有关测试页面响应的信息。

自定义规则

可以安装spatie/pest-expectations扩展辅助验证。

php
it('has valid phone number for chinesePhoneNumber rule',
+]);

可以在官网了解更多有关测试页面响应的信息。

自定义规则

可以安装spatie/pest-expectations扩展辅助验证。

php
it('has valid phone number for chinesePhoneNumber rule',
     fn ($value) => expect(new ChinesePhoneNumberRule())->toPassWith($value)
 )->with([
     [13800138000],
@@ -310,7 +310,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     expect($products)
         ->toBeInstanceOf(Collection::class)
         ->first()->toBeInstanceOf(Product::class);
-});

如果需要测试模型的 released() 访问的逻辑,可以如下进行相应测试:

php
it('only returns released courses for query scope', function () {
+});

如果需要测试模型的 released() 访问的逻辑,可以如下进行相应测试:

php
it('only returns released courses for query scope', function () {
     // Arrange
     Course::factory()->released()->create();
     Course::factory()->create();
@@ -334,7 +334,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
 }
// App\\Models\\Course.php
 public function scopeReleased($query) {
     return $query->where('released_at', '>=', now());
-}

另一个模型访问器的例子:

php
it('capitalizes the first character of the first name', function () {
+}

另一个模型访问器的例子:

php
it('capitalizes the first character of the first name', function () {
     // Arrange
     $user = User::factory()->create(['first_name' => 'christoph'])
 
@@ -360,7 +360,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     return Attribute::make(
         get: fn (string $value) => ucfirst($value),
     );
-}

邮件 Mail

邮件发送

在控制器代码逻辑处理时,将发送一封电子邮件。在测试中,可以通过发送请求并确保这封电子邮件已被发送。

php
it('sends email to podcast author', function() {
+}

邮件 Mail

邮件发送

在控制器代码逻辑处理时,将发送一封电子邮件。在测试中,可以通过发送请求并确保这封电子邮件已被发送。

php
it('sends email to podcast author', function() {
     // Arrange
     Mail::fake(); 
     $podcast = Podcast::factory()->create();
@@ -496,7 +496,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     Notification::assertSentTo(
         [$user], NewProductNotification::class
     );
-});

在上面的示例中测试了创建新产品时发送通知给用户。使用 artisan 方法来触发通知。

同样,通知 Notification::fake() 伪造它,确保没有发送实际的通知。

可以在官网了解更多有关测试通知的信息。

Actions

Action 只是具有一项特定工作的简单类,它是组织代码并将逻辑与控制器分开以保持它们干净的好方法。更多详情可以看Laravel Actions扩展。

php
// controller
+});

在上面的示例中测试了创建新产品时发送通知给用户。使用 artisan 方法来触发通知。

同样,通知 Notification::fake() 伪造它,确保没有发送实际的通知。

可以在官网了解更多有关测试通知的信息。

Actions

Action 只是具有一项特定工作的简单类,它是组织代码并将逻辑与控制器分开以保持它们干净的好方法。更多详情可以看Laravel Actions扩展。

php
// controller
 class PurchaseController extends Controller
 {
     public function __invoke(User $user, Product $product): void
@@ -572,7 +572,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     expect($user->products)
         ->toHaveCount(1)
         ->first()->id->toEqual($product->id);
-});

命令 Commands

可以通过直接触发命令来进行测试。

php
it('merges two accounts', function () {
+});

命令 Commands

可以通过直接触发命令来进行测试。

php
it('merges two accounts', function () {
     // Arrange
     $user = User::factory()->create();
     $userToBeMerged = User::factory()->create();
@@ -630,7 +630,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
         ->expectsQuestion('Please provide the user ID of the user you want to merge', $userToBeMerged->id)
         ->expectsOutput('Accounts merged successfully')
         ->assertSuccessful(); // 可以期待输出并确保命令成功,这意味着退出代码为 0。
-});

可以在官网了解更多有关测试命令的信息。

中间件 Middlewares

这里以一个路由中间件作为示例。源代码查看

php
<?php
+});

可以在官网了解更多有关测试命令的信息。

中间件 Middlewares

这里以一个路由中间件作为示例。源代码查看

php
<?php
 // tests/Unit/Http/Middleware/RedirectMiddlewareTest.php
 
 use App\\Models\\Redirect;
@@ -994,7 +994,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
         'userId' => 1,
         'userToBeMergedId' => 2,
     ]);
-})->throws(ModelNotFoundException::class);

可以使用 Pestthrows 方法确保抛出异常。

单元测试 Unit Tests

单元测试非常适合测试小段代码,例如单个方法。

不涉及其他依赖项。这使得它们非常快速且易于编写。

php
it('creates UserData object from paddle webhook call', function () {
+})->throws(ModelNotFoundException::class);

可以使用 Pestthrows 方法确保抛出异常。

单元测试 Unit Tests

单元测试非常适合测试小段代码,例如单个方法。

不涉及其他依赖项。这使得它们非常快速且易于编写。

php
it('creates UserData object from paddle webhook call', function () {
     // Arrange
     $payload = [
       'client_email' => 'test@test.com',
@@ -1122,7 +1122,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
         return $request->url() === 'https://christoph-rumpel.com/import'
             && $request['accessToken'] === 'faker-token';
     });
-});

可以在官网了解更多有关测试伪造 HTTP 调用的信息。

模拟依赖关系 mock

当使用具有依赖关系的代码时,模拟它们会很有帮助,这将使您专注于代码的逻辑而不是依赖项。

这也意味着模拟对于任何类型的测试都很有用。

在测试中希望重点测试是否发送了正确的电子邮件。

php
it('sends payment successful mail', function () {
+});

可以在官网了解更多有关测试伪造 HTTP 调用的信息。

模拟依赖关系 mock

当使用具有依赖关系的代码时,模拟它们会很有帮助,这将使您专注于代码的逻辑而不是依赖项。

这也意味着模拟对于任何类型的测试都很有用。

在测试中希望重点测试是否发送了正确的电子邮件。

php
it('sends payment successful mail', function () {
     // Arrange
     Mail::fake();
 
@@ -1170,7 +1170,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const u=
     ->expect(['dd', 'dump'])
     ->not->toBeUsed();
test('no forgotten debug statements')
     ->expect(['dd', 'dump'])
-    ->not->toBeUsed();

还可以定义更多规则。在官方文档中阅读有关它们的更多信息。

还可以参考 cachethq/core 仓库的测试代码风格。

定时任务 Schedules

断言定时任务一定会按照指定的规则执行。

php
<?php
+    ->not->toBeUsed();

还可以定义更多规则。在官方文档中阅读有关它们的更多信息。

还可以参考 cachethq/core 仓库的测试代码风格。

定时任务 Schedules

断言定时任务一定会按照指定的规则执行。

php
<?php
 // App\\Console\\Kernel
 
 // ...
diff --git a/assets/partials_testing.md.e6422a98.lean.js b/assets/partials_testing.md.b2dcd88d.lean.js
similarity index 100%
rename from assets/partials_testing.md.e6422a98.lean.js
rename to assets/partials_testing.md.b2dcd88d.lean.js
diff --git a/assets/tips_db-models-and-eloquent.md.6072c73a.js b/assets/tips_db-models-and-eloquent.md.cf99938b.js
similarity index 99%
rename from assets/tips_db-models-and-eloquent.md.6072c73a.js
rename to assets/tips_db-models-and-eloquent.md.cf99938b.js
index 8c32dcf82..f5e76b443 100644
--- a/assets/tips_db-models-and-eloquent.md.6072c73a.js
+++ b/assets/tips_db-models-and-eloquent.md.cf99938b.js
@@ -56,7 +56,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
      ->rawValue('YEAR(\`date_at\`)');
 
 $fullname = UserModel::where('id', $id)
-     ->rawValue('CONCAT(\`first_name\`, " ", \`last_name\`)');

scope 其他关系的模型范围

可以使用模型范围来定义一个相关的模型关联关系。

php
public function lessons(): HasMany
+     ->rawValue('CONCAT(\`first_name\`, " ", \`last_name\`)');

scope 其他关系的模型范围

可以使用模型范围来定义一个相关的模型关联关系。

php
public function lessons(): HasMany
 {
     return $this->hasMany(Lesson::class);
 }
@@ -78,7 +78,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
 }
public function scopePublished($query)
 {
     return $query->where('is_published', true);
-}

多个查询范围

可以在 Eloquent 查询中使用多个范围。

php
User::registeredWithinDays(30)->active()->get();
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
+}

多个查询范围

可以在 Eloquent 查询中使用多个范围。

php
User::registeredWithinDays(30)->active()->get();
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
     return $query->where('active', 1);
 }
  
@@ -98,7 +98,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
     DB::table('users')->update(['votes' => 1]);
  
     DB::table('posts')->delete();
-});

DB::afterCommit 事务处理

使用 DB::afterCommit() 方法,可以编写仅在事务提交时执行的代码,以及在事务回滚时丢弃的代码。

如果没有事务时,代码会立即执行。

php
class User extends Model
+});

DB::afterCommit 事务处理

使用 DB::afterCommit() 方法,可以编写仅在事务提交时执行的代码,以及在事务回滚时丢弃的代码。

如果没有事务时,代码会立即执行。

php
class User extends Model
 {
     protected static function booted()
     {
@@ -152,7 +152,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
 $allMedia = $videos->merge($images);
 
 // 在 Eloquent 集合中调用 \`toBase()\` 以使用基本合并方法
-$allMedia = $videos->toBase()->merge($images);

在 MySQL 上使用 Laravel 进行全文搜索

php
Schema::create('comments', function (Blueprint $table) {
+$allMedia = $videos->toBase()->merge($images);

在 MySQL 上使用 Laravel 进行全文搜索

php
Schema::create('comments', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->text('description');
@@ -232,7 +232,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
 {
     const CREATED_AT = 'create_time';
     const UPDATED_AT = 'update_time';
-}

更改 created_at 和 updated_at 的格式

可以在模型中添加一个方法,如下所示

php
protected function createdAtFormatted(): Attribute
+}

更改 created_at 和 updated_at 的格式

可以在模型中添加一个方法,如下所示

php
protected function createdAtFormatted(): Attribute
 {
     return Attribute::make(
         get: fn ($value, $attributes) => $attributes['created_at']->format('Y-m-d H:i:s'),
@@ -330,7 +330,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
     fn ($item) => $item->name[0]
 );
Company::all()->groupBy(
     fn ($item) => $item->name[0]
-);

从不更新列

如果有一个数据库列,只想设置一次并且不再更新,可以使用 mutator 对模型设置。

php
use Illuminate\\Database\\Eloquent\\Casts\\Attribute;
+);

从不更新列

如果有一个数据库列,只想设置一次并且不再更新,可以使用 mutator 对模型设置。

php
use Illuminate\\Database\\Eloquent\\Casts\\Attribute;
  
 class User extends Model
 {
@@ -392,7 +392,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
 });
Schema::create('users', function (Blueprint $table) {
     // $table->increments('id');
     $table->uuid('id')->unique();
-});
php
use Illuminate\\Database\\Eloquent\\Concerns\\HasUuids;
+});
php
use Illuminate\\Database\\Eloquent\\Concerns\\HasUuids;
 use Illuminate\\Database\\Eloquent\\Model;
  
 class Article extends Model
@@ -510,7 +510,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
 
 DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');
DB::statement('DROP TABLE users');
 
-DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

updateOrCreate 更新或创建

需要检查记录是否存在,然后更新它,或者创建一条新记录。

php
Flight::updateOrCreate(
+DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

updateOrCreate 更新或创建

需要检查记录是否存在,然后更新它,或者创建一条新记录。

php
Flight::updateOrCreate(
     ['departure' => 'Oakland', 'destination' => 'San Diego'],
     ['price' => 99, 'discounted' => 1]
 );
Flight::updateOrCreate(
@@ -842,7 +842,7 @@ import{_ as s,o as a,c as n,Q as l}from"./chunks/framework.16715cb7.js";const h=
     Book::query()
         ->withAvg('ratings as average_rating', 'rating')
         ->orderByDesc('average_rating');
-}

返回事务结果

如果有一个数据库事务并希望返回其结果:

php
$invoice = DB::transaction(function () {
+}

返回事务结果

如果有一个数据库事务并希望返回其结果:

php
$invoice = DB::transaction(function () {
     $invoice = Invoice::create(...);
     $invoice->items()->attach(...);
  
diff --git a/assets/tips_db-models-and-eloquent.md.6072c73a.lean.js b/assets/tips_db-models-and-eloquent.md.cf99938b.lean.js
similarity index 100%
rename from assets/tips_db-models-and-eloquent.md.6072c73a.lean.js
rename to assets/tips_db-models-and-eloquent.md.cf99938b.lean.js
diff --git a/assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.js b/assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.js
similarity index 97%
rename from assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.js
rename to assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.js
index 6922c74ca..a9e59f64f 100644
--- a/assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.js
+++ b/assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.js
@@ -1,4 +1,4 @@
-import{_ as s,o as a,c as n,Q as p}from"./chunks/framework.16715cb7.js";const o="/laravel-study/assets/speed-comparison-preview.96f332b1.png",h=JSON.parse('{"title":"优化 Factory 数据库批量插入","description":"","frontmatter":{},"headers":[],"relativePath":"tips/optimize-factory-database-batch-insert.md","filePath":"tips/optimize-factory-database-batch-insert.md","lastUpdated":1695291452000}'),l={name:"tips/optimize-factory-database-batch-insert.md"},t=p(`

优化 Factory 数据库批量插入

在创建测试数据时,使用批量插入数据库记录,而不是在单独的插入每一行,因为这将使您的测试更快。

php
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
+import{_ as s,o as a,c as n,Q as p}from"./chunks/framework.16715cb7.js";const o="/laravel-study/assets/speed-comparison-preview.96f332b1.png",g=JSON.parse('{"title":"优化 Factory 数据库批量插入","description":"","frontmatter":{},"headers":[],"relativePath":"tips/optimize-factory-database-batch-insert.md","filePath":"tips/optimize-factory-database-batch-insert.md","lastUpdated":1695291452000}'),l={name:"tips/optimize-factory-database-batch-insert.md"},t=p(`

优化 Factory 数据库批量插入

在创建测试数据时,使用批量插入数据库记录,而不是在单独的插入每一行,因为这将使您的测试更快。

php
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
 Post::factory()->count(1000)->create();
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
 Post::factory()->count(1000)->create();
php
Post::query()->insert(
     Post::factory()->count(1000)->make()->toArray()
@@ -24,4 +24,4 @@ import{_ as s,o as a,c as n,Q as p}from"./chunks/framework.16715cb7.js";const o=
 Post::query()->insert(
     Post::factory()->count(1000)->make()->toArray()
 );
-ray(microtime(true) - $start); // 0.15621304512024

',7),e=[t];function c(r,y,E,i,F,d){return a(),n("div",null,e)}const g=s(l,[["render",c]]);export{h as __pageData,g as default}; +ray(microtime(true) - $start); // 0.15621304512024

',7),e=[t];function c(r,y,E,i,F,d){return a(),n("div",null,e)}const h=s(l,[["render",c]]);export{g as __pageData,h as default}; diff --git a/assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.lean.js b/assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.lean.js similarity index 75% rename from assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.lean.js rename to assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.lean.js index 57158a245..d621f902d 100644 --- a/assets/tips_optimize-factory-database-batch-insert.md.9d93f7ee.lean.js +++ b/assets/tips_optimize-factory-database-batch-insert.md.6cd4dbb4.lean.js @@ -1 +1 @@ -import{_ as s,o as a,c as n,Q as p}from"./chunks/framework.16715cb7.js";const o="/laravel-study/assets/speed-comparison-preview.96f332b1.png",h=JSON.parse('{"title":"优化 Factory 数据库批量插入","description":"","frontmatter":{},"headers":[],"relativePath":"tips/optimize-factory-database-batch-insert.md","filePath":"tips/optimize-factory-database-batch-insert.md","lastUpdated":1695291452000}'),l={name:"tips/optimize-factory-database-batch-insert.md"},t=p("",7),e=[t];function c(r,y,E,i,F,d){return a(),n("div",null,e)}const g=s(l,[["render",c]]);export{h as __pageData,g as default}; +import{_ as s,o as a,c as n,Q as p}from"./chunks/framework.16715cb7.js";const o="/laravel-study/assets/speed-comparison-preview.96f332b1.png",g=JSON.parse('{"title":"优化 Factory 数据库批量插入","description":"","frontmatter":{},"headers":[],"relativePath":"tips/optimize-factory-database-batch-insert.md","filePath":"tips/optimize-factory-database-batch-insert.md","lastUpdated":1695291452000}'),l={name:"tips/optimize-factory-database-batch-insert.md"},t=p("",7),e=[t];function c(r,y,E,i,F,d){return a(),n("div",null,e)}const h=s(l,[["render",c]]);export{g as __pageData,h as default}; diff --git a/assets/tips_reuse-the-environment-variable-value.md.7be73538.js b/assets/tips_reuse-the-environment-variable-value.md.60398b96.js similarity index 81% rename from assets/tips_reuse-the-environment-variable-value.md.7be73538.js rename to assets/tips_reuse-the-environment-variable-value.md.60398b96.js index b380afe20..49550d8ed 100644 --- a/assets/tips_reuse-the-environment-variable-value.md.7be73538.js +++ b/assets/tips_reuse-the-environment-variable-value.md.60398b96.js @@ -1,5 +1,5 @@ -import{_ as e,o as a,c as s,Q as t}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1695291452000}'),l={name:"tips/reuse-the-environment-variable-value.md"},n=t(`

重用环境变量值

当环境变量中存在重复的变量值时,可以重用环境变量值。

可以使用此语法重用它们,而不是重写这些值。

dotenv
APP_URL=https://laravel-tips.test
+import{_ as e,o as a,c as s,Q as t}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1695291452000}'),n={name:"tips/reuse-the-environment-variable-value.md"},p=t(`

重用环境变量值

当环境变量中存在重复的变量值时,可以重用环境变量值。

可以使用此语法重用它们,而不是重写这些值。

dotenv
APP_URL=https://laravel-tips.test
 ADMIN_URL=https://laravel-tips.test
APP_URL=https://laravel-tips.test
 ADMIN_URL=https://laravel-tips.test
dotenv
APP_URL=https://laravel-tips.test
 ADMIN_URL="\${APP_URL}"
APP_URL=https://laravel-tips.test
-ADMIN_URL="\${APP_URL}"
`,4),p=[n];function o(i,c,r,d,v,h){return a(),s("div",null,p)}const b=e(l,[["render",o]]);export{u as __pageData,b as default}; +ADMIN_URL="\${APP_URL}"
`,4),l=[p];function o(i,c,r,d,v,_){return a(),s("div",null,l)}const b=e(n,[["render",o]]);export{u as __pageData,b as default}; diff --git a/assets/tips_reuse-the-environment-variable-value.md.7be73538.lean.js b/assets/tips_reuse-the-environment-variable-value.md.60398b96.lean.js similarity index 62% rename from assets/tips_reuse-the-environment-variable-value.md.7be73538.lean.js rename to assets/tips_reuse-the-environment-variable-value.md.60398b96.lean.js index 36588a444..8d766aa9f 100644 --- a/assets/tips_reuse-the-environment-variable-value.md.7be73538.lean.js +++ b/assets/tips_reuse-the-environment-variable-value.md.60398b96.lean.js @@ -1 +1 @@ -import{_ as e,o as a,c as s,Q as t}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1695291452000}'),l={name:"tips/reuse-the-environment-variable-value.md"},n=t("",4),p=[n];function o(i,c,r,d,v,h){return a(),s("div",null,p)}const b=e(l,[["render",o]]);export{u as __pageData,b as default}; +import{_ as e,o as a,c as s,Q as t}from"./chunks/framework.16715cb7.js";const u=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1695291452000}'),n={name:"tips/reuse-the-environment-variable-value.md"},p=t("",4),l=[p];function o(i,c,r,d,v,_){return a(),s("div",null,l)}const b=e(n,[["render",o]]);export{u as __pageData,b as default}; diff --git a/collections/all.html b/collections/all.html index 4ddfc5b03..1aa0e4ecd 100644 --- a/collections/all.html +++ b/collections/all.html @@ -11,7 +11,7 @@ - + @@ -23,7 +23,7 @@ collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]
collect([1, 2, 3, 4])->all(); // [1, 2, 3, 4]
 
 // 上面 `all` 方法的调用类似于 `toArray` 方法
-collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]

与 toArray 的区别

all 方法与 toArray 方法的区别在于嵌套集合在调用方法后生成的结果不同。

php
// 使用 all 方法只会将集合中首层的元素格式化为数组
+collect([1, 2, 3, 4])->toArray(); // [1, 2, 3, 4]

与 toArray 的区别

all 方法与 toArray 方法的区别在于嵌套集合在调用方法后生成的结果不同。

php
// 使用 all 方法只会将集合中首层的元素格式化为数组
 collect([collect([1, 2, 3, 4]), collect([1, 2, 3, 4])])->all();
 
 /**
@@ -64,7 +64,7 @@
  [1, 2, 3, 4],
 ]
 */

关联方法

- + \ No newline at end of file diff --git a/collections/avg.html b/collections/avg.html index 91df2a5e8..d703645e6 100644 --- a/collections/avg.html +++ b/collections/avg.html @@ -11,13 +11,13 @@ - + -
Skip to content

avg

返回数组中给定键的值的平均值

一些示例

php
// 获取一维数组
+    
Skip to content

avg

返回数组中给定键的值的平均值

一些示例

php
// 获取一维数组
 collect([10, 20, 30])->average(); // 20
 
 // 获取二维数组的平均值
@@ -68,7 +68,7 @@
   ->average(
     fn ($value) => $value['price'] + $value['tax']
 ); // 20750

关联方法

- + \ No newline at end of file diff --git a/collections/chunk.html b/collections/chunk.html index ac2e80222..85151c580 100644 --- a/collections/chunk.html +++ b/collections/chunk.html @@ -11,13 +11,13 @@ - + -
Skip to content

chuck

将集合拆分为多个指定大小的集合组。

一些示例

php
collect([1, 2, 3, 4, 5, 6, 7, 8])->chunk(4); 
+    
Skip to content

chuck

将集合拆分为多个指定大小的集合组。

一些示例

php
collect([1, 2, 3, 4, 5, 6, 7, 8])->chunk(4); 
 /**
 => Illuminate\Support\Collection {#1089
      all: [
@@ -72,7 +72,7 @@
      ],
    }
 */

相关方法

- + \ No newline at end of file diff --git a/collections/chunkWhile.html b/collections/chunkWhile.html index 7cbdf6f5e..d204b095f 100644 --- a/collections/chunkWhile.html +++ b/collections/chunkWhile.html @@ -26,7 +26,7 @@ $collection->chunkWhile( fn (string $value, int $key, Collection $chunk) => $value === $chunk->last() )->toArray(); // [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]

每次循环时,闭包中的 $chunk 变量都会填充为前面已循环的所有元素的集合。

- + \ No newline at end of file diff --git a/collections/collapse.html b/collections/collapse.html index ed39ef614..b26321efe 100644 --- a/collections/collapse.html +++ b/collections/collapse.html @@ -11,13 +11,13 @@ - + -
Skip to content

collapse

将数组集合折叠成单个集合。

相关示例

php
$collections = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
+    
Skip to content

collapse

将数组集合折叠成单个集合。

相关示例

php
$collections = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
 
 collect($collections)->collapse(); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
@@ -38,7 +38,7 @@
 
 // 上面 `collapse` 方法的使用类似于 `flatten(1)` 方法的调用结果
 collect($collections)->flatten(1); // [[1], [2], [3], 3, 4, 5]

关联方法

- + \ No newline at end of file diff --git a/collections/collect.html b/collections/collect.html index 90ee7c243..adf26bf96 100644 --- a/collections/collect.html +++ b/collections/collect.html @@ -42,7 +42,7 @@ $collection = $lazyCollection->collect(); get_class($collection); // 'Illuminate\Support\Collection'
- + \ No newline at end of file diff --git a/collections/combine.html b/collections/combine.html index 105233042..1e69ebd87 100644 --- a/collections/combine.html +++ b/collections/combine.html @@ -30,7 +30,7 @@ # 合并二维数组 collect(['key1', 'key2']) ->combine([[123], [456]]); // ["key1" => [123], "key2" => [456]]

如果待合并的两个数组个数不匹配,则会抛出 ValueError 错误。

- + \ No newline at end of file diff --git a/collections/concat.html b/collections/concat.html index 84b581605..9a2d3c9bb 100644 --- a/collections/concat.html +++ b/collections/concat.html @@ -32,7 +32,7 @@ // 如果需要保持附加元素的key,可以使用 merge 方法 collect(['key1' => 'value1'])->merge(['key2' => 'value2']); // ["key1" => "value1", "key2" => "value2"]

关联方法

- + \ No newline at end of file diff --git a/collections/contains.html b/collections/contains.html index ab6c78d3e..7eaf50070 100644 --- a/collections/contains.html +++ b/collections/contains.html @@ -11,13 +11,13 @@ - + -
Skip to content

contains

判断集合是否包含给定的项目,返回最后匹配的布尔值。

php
collect(['value'])->contains('value1'); // false
+    
Skip to content

contains

判断集合是否包含给定的项目,返回最后匹配的布尔值。

php
collect(['value'])->contains('value1'); // false
 collect(['value'])->contains('value'); // true
 collect(['key' => 'value'])->contains('value'); // true
collect(['value'])->contains('value1'); // false
 collect(['value'])->contains('value'); // true
@@ -42,7 +42,7 @@
 
 $collection->contains(fn ($value, $key) => $value > 4); // true
 $collection->contains(fn ($value, $key) => $value > 5); // false

相关方法

- + \ No newline at end of file diff --git a/collections/containsOneItem.html b/collections/containsOneItem.html index 4952ad688..5c84d5cf3 100644 --- a/collections/containsOneItem.html +++ b/collections/containsOneItem.html @@ -26,7 +26,7 @@ collect(['1'])->containsOneItem(); // true collect(['1', '2'])->containsOneItem(); // false

相关方法

- + \ No newline at end of file diff --git a/collections/containsStrict.html b/collections/containsStrict.html index 107e26c36..6941c95e8 100644 --- a/collections/containsStrict.html +++ b/collections/containsStrict.html @@ -24,7 +24,7 @@ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ])->containsStrict('price', '100'); // false

如上例所示,集合中对应的值存在,但是值类型不一致也会返回 false

相关方法

- + \ No newline at end of file diff --git a/collections/count.html b/collections/count.html index d63310787..de049a101 100644 --- a/collections/count.html +++ b/collections/count.html @@ -18,7 +18,7 @@
Skip to content

count

返回该集合内的项目总数

php
collect([1, 2, 3, 4])->count(); // 4
collect([1, 2, 3, 4])->count(); // 4
- + \ No newline at end of file diff --git a/collections/countBy.html b/collections/countBy.html index e04b099e8..8bd9bf808 100644 --- a/collections/countBy.html +++ b/collections/countBy.html @@ -11,13 +11,13 @@ - + -
Skip to content

countBy

计算集合中值的出现次数,默认情况下,该方法计算每个元素的出现次数,允许计算集合中某些"类型"的元素。

php
collect([1, 2, 2, 2, 3])->countBy();
+    
Skip to content

countBy

计算集合中值的出现次数,默认情况下,该方法计算每个元素的出现次数,允许计算集合中某些"类型"的元素。

php
collect([1, 2, 2, 2, 3])->countBy();
 
 // [1 => 1, 2 => 3, 3 => 1]
collect([1, 2, 2, 2, 3])->countBy();
 
@@ -26,7 +26,7 @@
 ); // ['gmail.com' => 2, 'yahoo.com' => 1]
collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com'])->countBy(
     fn (string $email) => substr(strrchr($email, "@"), 1)
 ); // ['gmail.com' => 2, 'yahoo.com' => 1]

相关方法

- + \ No newline at end of file diff --git a/collections/crossJoin.html b/collections/crossJoin.html index d538a14dc..23225d5a1 100644 --- a/collections/crossJoin.html +++ b/collections/crossJoin.html @@ -62,7 +62,7 @@ [2, "b", "d"] ] */
- + \ No newline at end of file diff --git a/collections/dd.html b/collections/dd.html index 9dea0ab18..0b63b1912 100644 --- a/collections/dd.html +++ b/collections/dd.html @@ -44,7 +44,7 @@ 22 => 12 ] */

如果不希望终止脚本的执行,使用 dump 方法即可。

相关方法

- + \ No newline at end of file diff --git a/collections/diff.html b/collections/diff.html index 8ed7be4db..9786917b0 100644 --- a/collections/diff.html +++ b/collections/diff.html @@ -22,7 +22,7 @@ collect(['apples', 'bananas'])->diff(['pears', 'bananas']); // ["apples"]
collect([1, 2, 3])->diff([2, 4, 6]); // [1, 3]
 
 collect(['apples', 'bananas'])->diff(['pears', 'bananas']); // ["apples"]

相关方法

- + \ No newline at end of file diff --git a/collections/diffAssoc.html b/collections/diffAssoc.html index d82e1d5f2..35b42dda8 100644 --- a/collections/diffAssoc.html +++ b/collections/diffAssoc.html @@ -20,7 +20,7 @@
Skip to content

diffAssoc

与另外一个集合或基于它的键和值的 PHP 数组进行比较,返回原集合不存在于给定集合中的键值对。

php
collect([10 => 'apples', 20 => 'bananas'])
     ->diffAssoc([30 => 'pears', 20 => 'bananas']); // [10 => "apples"]
collect([10 => 'apples', 20 => 'bananas'])
     ->diffAssoc([30 => 'pears', 20 => 'bananas']); // [10 => "apples"]

相关方法

- + \ No newline at end of file diff --git a/collections/diffAssocUsing.html b/collections/diffAssocUsing.html index ceb7f5525..8fe23d59f 100644 --- a/collections/diffAssocUsing.html +++ b/collections/diffAssocUsing.html @@ -40,7 +40,7 @@ ['123AG' => 10], fn ($a, $b) => (str_replace('-', '', $a) === $b) ? 0 : -1 ); // ["456A-G" => 25]

相关方法

- + \ No newline at end of file diff --git a/collections/diffKeys.html b/collections/diffKeys.html index 720026131..30fe0c1f4 100644 --- a/collections/diffKeys.html +++ b/collections/diffKeys.html @@ -20,7 +20,7 @@
Skip to content

diffKeys

与另外一个集合或 PHP 数组的「键」进行比较,返回原集合中存在而给定的集合中不存在「键」所对应的键值对。

php
collect([10 => 'apples', 20 => 'pears'])
     ->diffKeys([30 => 'pears', 20 => 'bananas']); // [10 => "apples"]
collect([10 => 'apples', 20 => 'pears'])
     ->diffKeys([30 => 'pears', 20 => 'bananas']); // [10 => "apples"]

相关方法

- + \ No newline at end of file diff --git a/collections/diffKeysUsing.html b/collections/diffKeysUsing.html index 7b7504860..770cd2b8d 100644 --- a/collections/diffKeysUsing.html +++ b/collections/diffKeysUsing.html @@ -40,7 +40,7 @@ ['123AG' => 20], fn ($a, $b) => str_replace('-', '', $a) === $b ? 0 : -1 ); // ["456A-G" => 25]

相关方法

- + \ No newline at end of file diff --git a/collections/diffUsing.html b/collections/diffUsing.html index c03c4c6d1..dbcb999a7 100644 --- a/collections/diffUsing.html +++ b/collections/diffUsing.html @@ -42,7 +42,7 @@ ['123AG'], fn ($a, $b) => (str_replace('-', '', $a) === $b) ? 0 : -1 ); // [1 => "456A-G"]

相关方法

- + \ No newline at end of file diff --git a/collections/doesntContain.html b/collections/doesntContain.html index c3683899d..80044a5ec 100644 --- a/collections/doesntContain.html +++ b/collections/doesntContain.html @@ -30,7 +30,7 @@ collect(['name' => 'Desk', 'price' => 100]) ->doesntContain('Desk'); // false

相关方法

- + \ No newline at end of file diff --git a/collections/dump.html b/collections/dump.html index dc3961a1b..27d445e63 100644 --- a/collections/dump.html +++ b/collections/dump.html @@ -30,7 +30,7 @@ ->reverse() ->dump() // [0 => 10, 1 => 20, 2 => 30, 3 => 40] ->first();

可以通过在链式调用集合方法的时候使用 dump 打印出当前的集合状态,以便查看集合的状态。

如果需要在某处停止链式调用,建议使用 dd 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/duplicates.html b/collections/duplicates.html index 1b3cfc887..3a99d2b6f 100644 --- a/collections/duplicates.html +++ b/collections/duplicates.html @@ -28,7 +28,7 @@ ['email' => 'james@example.com', 'position' => 'Designer'], ['email' => 'victoria@example.com', 'position' => 'Developer'], ])->duplicates('position'); // [2 => 'Developer']

相关方法

- + \ No newline at end of file diff --git a/collections/duplicatesStrict.html b/collections/duplicatesStrict.html index 22cb00abe..43db7057a 100644 --- a/collections/duplicatesStrict.html +++ b/collections/duplicatesStrict.html @@ -46,7 +46,7 @@ ['email' => 'james@example.com', 'status' => 1], ['email' => 'victoria@example.com', 'status' => 1], ])->duplicates('status'); // [1 => 1, 2 => 1]

相关方法

- + \ No newline at end of file diff --git a/collections/each.html b/collections/each.html index c7d235e2f..697c3b7bd 100644 --- a/collections/each.html +++ b/collections/each.html @@ -82,7 +82,7 @@ // "We have banners 45 in our California store." // "We have apples 20 in our Florida store." // "We have coconuts 60 in our Texas store."

可以看到通过调用 eachSpread 方法,在回调函数中有更明确的变量可供使用,变得更加有寓意话。

相关方法

- + \ No newline at end of file diff --git a/collections/eachSpread.html b/collections/eachSpread.html index 4d40546f3..d4cf40a99 100644 --- a/collections/eachSpread.html +++ b/collections/eachSpread.html @@ -60,7 +60,7 @@ }); // "We have banners 45 in our California store."

可以看到当在回掉函数中当返回 false 时,循环终止。

相关方法

- + \ No newline at end of file diff --git a/collections/every.html b/collections/every.html index 8e6f0aee1..7d58175e8 100644 --- a/collections/every.html +++ b/collections/every.html @@ -18,7 +18,7 @@
Skip to content

every

可用于验证集合中每一个元素都通过回调测试。

php
collect([1, 2, 3, 4])->every(fn ($value, $key) => $value > 2); // false
collect([1, 2, 3, 4])->every(fn ($value, $key) => $value > 2); // false

如果给定的集合为空集合,则无论 every 方法的回调中表达式的结果,都将返回 true

php
collect([])->every(fn ($value, $key) => $value > 2); // true
collect([])->every(fn ($value, $key) => $value > 2); // true

相关方法

- + \ No newline at end of file diff --git a/collections/examples/README.html b/collections/examples/README.html index 6e84b7283..2e2689acc 100644 --- a/collections/examples/README.html +++ b/collections/examples/README.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/collections/examples/format-calculate-the-data-of-the-two-arrays.html b/collections/examples/format-calculate-the-data-of-the-two-arrays.html index becf60af6..a3eae8af7 100644 --- a/collections/examples/format-calculate-the-data-of-the-two-arrays.html +++ b/collections/examples/format-calculate-the-data-of-the-two-arrays.html @@ -146,7 +146,7 @@ ] } */ - + \ No newline at end of file diff --git a/collections/examples/format-github-events-score.html b/collections/examples/format-github-events-score.html index fd1eed13e..39bdc2464 100644 --- a/collections/examples/format-github-events-score.html +++ b/collections/examples/format-github-events-score.html @@ -11,7 +11,7 @@ - + @@ -69,7 +69,7 @@ } } -dd($score); // 输出 134

使用 pluckmapsum 方法

php
$events = collect(
+dd($score); // 输出 134

使用 pluckmapsum 方法

php
$events = collect(
   Http::get('https://api.github.com/users/curder/events')->json()
 );
 
@@ -173,7 +173,7 @@
       'IssueCommentEvent' => 2,
     ])->get($eventType, 1); // 如果不存在则默认等于1
   })
-  ->sum();

封装 GitHubScore 类

php
$events = collect(
+  ->sum();

封装 GitHubScore 类

php
$events = collect(
     Http::get('https://api.github.com/users/curder/events')->json()
 );
 
@@ -238,7 +238,7 @@
     ])->get($eventType, $default_value); // 如果不存在则默认等于1
   }
 }
- + \ No newline at end of file diff --git a/collections/examples/get-the-corresponding-key-by-value.html b/collections/examples/get-the-corresponding-key-by-value.html index 168e0c060..bd20f3d84 100644 --- a/collections/examples/get-the-corresponding-key-by-value.html +++ b/collections/examples/get-the-corresponding-key-by-value.html @@ -42,7 +42,7 @@ if (collect($messages)->contains('val2')) { $res = collect($messages)->search('val2'); // key2 } - + \ No newline at end of file diff --git a/collections/examples/map-format.html b/collections/examples/map-format.html index a9d81bb46..2a5fda18a 100644 --- a/collections/examples/map-format.html +++ b/collections/examples/map-format.html @@ -190,7 +190,7 @@ ], } */ - + \ No newline at end of file diff --git a/collections/examples/markdown-format.html b/collections/examples/markdown-format.html index d44c24883..9546419ed 100644 --- a/collections/examples/markdown-format.html +++ b/collections/examples/markdown-format.html @@ -104,7 +104,7 @@ - But there should not have blank in the key of config or .env file. """ */ - + \ No newline at end of file diff --git a/collections/examples/order-info-summary.html b/collections/examples/order-info-summary.html index 2c5902126..317929afc 100644 --- a/collections/examples/order-info-summary.html +++ b/collections/examples/order-info-summary.html @@ -11,7 +11,7 @@ - + @@ -131,7 +131,7 @@ 'qty' => 3, 'customer_name'=>'Mandy', ], -];
php
collect($orders)->groupBy('date');
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
+];
php
collect($orders)->groupBy('date');
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
 );
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
@@ -144,7 +144,7 @@
         fn ($item) => $item['item_unit_price'] * $item['qty']
     )
 );
- + \ No newline at end of file diff --git a/collections/examples/using-reduce-create-lookup-array.html b/collections/examples/using-reduce-create-lookup-array.html index 07b77d0e0..dfe0df66f 100644 --- a/collections/examples/using-reduce-create-lookup-array.html +++ b/collections/examples/using-reduce-create-lookup-array.html @@ -11,7 +11,7 @@ - + @@ -57,7 +57,7 @@ 'example' => 'example@example.com', 'Lucy' => 'lucy@example.com', 'Taylor'=> 'toylor@laravel.com' -];

一些方法

php
collect($employees)->pluck('email', 'name'); 
+];

一些方法

php
collect($employees)->pluck('email', 'name'); 
 
 // ["example" => "example@exmaple.com", "Lucy" => "lucy@example.com", "Taylor" => "toylor@laravel.com"]
collect($employees)->pluck('email', 'name'); 
 
@@ -84,7 +84,7 @@
 }, []);
 
 // ["example" => "example@exmaple.com", "Lucy" => "lucy@example.com", "Taylor" => "toylor@laravel.com"]
- + \ No newline at end of file diff --git a/collections/examples/using-sum-method.html b/collections/examples/using-sum-method.html index edac9a7a3..98a3a1076 100644 --- a/collections/examples/using-sum-method.html +++ b/collections/examples/using-sum-method.html @@ -100,7 +100,7 @@ ->sum('price');
collect($orders)
     ->flatMap(fn($order) => $order['order_products'])
     ->sum('price');
- + \ No newline at end of file diff --git a/collections/except.html b/collections/except.html index 036edb5a8..d479060be 100644 --- a/collections/except.html +++ b/collections/except.html @@ -28,7 +28,7 @@ 'discount', 'name' ]); // ["product_id" => 1]

与之相反操作是 only 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/filter.html b/collections/filter.html index 5a51b98c8..c6adf5ebf 100644 --- a/collections/filter.html +++ b/collections/filter.html @@ -26,7 +26,7 @@ $collection->dump(); // [0 => 1, 1 => 2, 2 => 3, 3 => 4] $newCollection->dd(); // [1 => 2, 3 => 4]

filter 相反的方法,可以查看 reject 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/first.html b/collections/first.html index d3dc1389c..f0613b85d 100644 --- a/collections/first.html +++ b/collections/first.html @@ -11,20 +11,20 @@ - + -
Skip to content

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
+    
Skip to content

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
 collect([1, 2, 3, 4])->first(fn ($element) => $element > 3); // 4
// 从集合左往右遍历,满足条件元素被返回。
 collect([1, 2, 3, 4])->first(fn ($element) => $element > 3); // 4
php
// 当通过回调函数遍历集合没有满足条件的返回值时,默认值将会被返回
 collect([1, 2, 3, 4])->first(fn ($item) => $item < 1, 1000); // 1000
 collect([])->first(null, 1000); // 1000
// 当通过回调函数遍历集合没有满足条件的返回值时,默认值将会被返回
 collect([1, 2, 3, 4])->first(fn ($item) => $item < 1, 1000); // 1000
 collect([])->first(null, 1000); // 1000

如果需要返回最后一个元素可以使用 last 方法。

其它方法

- + \ No newline at end of file diff --git a/collections/firstOrFail.html b/collections/firstOrFail.html index 2cdfe353b..abe282193 100644 --- a/collections/firstOrFail.html +++ b/collections/firstOrFail.html @@ -28,7 +28,7 @@ ->firstOrFail( fn (int $value, int $key) => $value > 5 ); // Throws ItemNotFoundException...

相关方法

- + \ No newline at end of file diff --git a/collections/firstWhere.html b/collections/firstWhere.html index 95f094a21..def00f854 100644 --- a/collections/firstWhere.html +++ b/collections/firstWhere.html @@ -11,13 +11,13 @@ - + -
Skip to content

firstWhere

返回给定键值对的第一个元素

php
collect([
+    
Skip to content

firstWhere

返回给定键值对的第一个元素

php
collect([
   ['product' => 'apples', 'price' => 50],
   ['product' => 'pears', 'price' => 50],
   ['product' => 'banners', 'price' => 50],
@@ -52,7 +52,7 @@
   ['product' => 'banners', 'price' => 50],
   ['product' => 'coconuts', 'price' => 80],
 ])->firstWhere('price', '>=', 70); // ["product" => "coconuts", "price" => 80]

相关方法

- + \ No newline at end of file diff --git a/collections/flatMap.html b/collections/flatMap.html index dc6c0f050..6422bebaa 100644 --- a/collections/flatMap.html +++ b/collections/flatMap.html @@ -30,7 +30,7 @@ ])->flatMap( fn ($values) => array_map('strtoupper', $values) ); // ["name" => "SALLY", "school" => "ARKANSAS", "age" => "28"]

相关方法

- + \ No newline at end of file diff --git a/collections/flatten.html b/collections/flatten.html index 33552cdcf..d798fbaaa 100644 --- a/collections/flatten.html +++ b/collections/flatten.html @@ -42,7 +42,7 @@ ["name" => "Galaxy S7", "brand" => "Samsung"] ] */

在这个例子里,调用 flatten 方法时不传入深度参数的话也会将嵌套数组转成一维的。

然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung'],传入深度参数能限制设置返回数组的层数。

有时候需要对数据进行分组可以使用 groupBy 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/flip.html b/collections/flip.html index d5920476c..b9fb81473 100644 --- a/collections/flip.html +++ b/collections/flip.html @@ -22,7 +22,7 @@ // ["taylor" => "name", "laravel" => "framework"]
collect(['name' => 'taylor', 'framework' => 'laravel'])->flip();
 
 // ["taylor" => "name", "laravel" => "framework"]

值得注意的是集合的值必须是字符串或者整型,否则会抛出警告。

- + \ No newline at end of file diff --git a/collections/forPage.html b/collections/forPage.html index 72c28591a..cd89c846a 100644 --- a/collections/forPage.html +++ b/collections/forPage.html @@ -20,7 +20,7 @@
Skip to content

forPage

返回给定页码上显示的项目的新集合。

php
collect([1, 2, 3, 4, 5, 6, 7, 8, 9])
     ->forPage(page: 2, perPage: 3); // [3 => 4, 4 => 5, 5 => 6]
collect([1, 2, 3, 4, 5, 6, 7, 8, 9])
     ->forPage(page: 2, perPage: 3); // [3 => 4, 4 => 5, 5 => 6]
  • 参数一:当前页面
  • 参数二:每页显示条目数
- + \ No newline at end of file diff --git a/collections/forget.html b/collections/forget.html index 0f99a8ee0..f91bcf8ca 100644 --- a/collections/forget.html +++ b/collections/forget.html @@ -36,7 +36,7 @@ $newCollection->dump(); // ["framework" => "laravel"] $collection->dd(); // ["framework" => "laravel"]

相关方法

- + \ No newline at end of file diff --git a/collections/get.html b/collections/get.html index 455b960aa..dc433464b 100644 --- a/collections/get.html +++ b/collections/get.html @@ -11,13 +11,13 @@ - + -
Skip to content

get

获取一维数组给定键的集合项。如果该键不存在,则返回 null

php
collect(['name' => 'taylor', 'framework' => 'laravel'])
+    
Skip to content

get

获取一维数组给定键的集合项。如果该键不存在,则返回 null

php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('name'); // "taylor"
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('name'); // "taylor"
php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('foo', 'bar'); // bar
collect(['name' => 'taylor', 'framework' => 'laravel'])
@@ -38,7 +38,7 @@
             return 'bar';
         }
     ); // bar

相关方法

- + \ No newline at end of file diff --git a/collections/groupBy.html b/collections/groupBy.html index b189934eb..09175a25f 100644 --- a/collections/groupBy.html +++ b/collections/groupBy.html @@ -188,7 +188,7 @@ ] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/has.html b/collections/has.html index 2d9e5d05d..9fc53cba4 100644 --- a/collections/has.html +++ b/collections/has.html @@ -26,7 +26,7 @@ $collection->has('product'); // true $collection->has(['product', 'amount']); // true $collection->has(['amount', 'price']); // false

相关方法

- + \ No newline at end of file diff --git a/collections/hasAny.html b/collections/hasAny.html index 47597b620..8a10499d4 100644 --- a/collections/hasAny.html +++ b/collections/hasAny.html @@ -24,7 +24,7 @@ $collection->hasAny(['product', 'price']); // true $collection->hasAny(['name', 'price']); // false

相关方法

- + \ No newline at end of file diff --git a/collections/implode.html b/collections/implode.html index 180393134..3c5c8d8c3 100644 --- a/collections/implode.html +++ b/collections/implode.html @@ -24,7 +24,7 @@ ['account_id' => 1, 'product' => 'Desk'], ['account_id' => 2, 'product' => 'Chair'], ])->implode('product', ', '); // "Desk, Chair"

其参数取决于集合中项目的类型。

如果集合包含数组或对象,应该传入希望连接的属性的键,以及希望放在值之间用来「拼接」的字符串

集合包含简单的字符串或数值,只需要传入「拼接」用的字符串作为该方法的唯一参数即可。

php
collect([1, 2, 3, 4, 5])->implode('-'); // "1-2-3-4-5"
collect([1, 2, 3, 4, 5])->implode('-'); // "1-2-3-4-5"

相关方法

- + \ No newline at end of file diff --git a/collections/index.html b/collections/index.html index 212833901..0f1077208 100644 --- a/collections/index.html +++ b/collections/index.html @@ -32,7 +32,7 @@ // 简单使用 collect([1, 2, 3]); // Illuminate\Support\Collection {#1070 all: [1, 2, 3]}

在JS中使用集合操作

如果在 JavaScript 中也需要使用类似的数组操作,具体可以可以参考 ecrmnn/collect.js

- + \ No newline at end of file diff --git a/collections/intersect.html b/collections/intersect.html index fecbd7b44..c337ef65a 100644 --- a/collections/intersect.html +++ b/collections/intersect.html @@ -24,7 +24,7 @@ ->intersect(['Desk', 'Chair', 'Bookcase']); // [ "Desk", "Chair"]

不改变原数组或集合。

相关方法

- + \ No newline at end of file diff --git a/collections/intersectByKeys.html b/collections/intersectByKeys.html index 9889ae57c..a0417a8f0 100644 --- a/collections/intersectByKeys.html +++ b/collections/intersectByKeys.html @@ -34,7 +34,7 @@ 'type' => 'tab', 'year' => 2011, ]); // ["type" => "screen", "year" => 2009]

相关方法

- + \ No newline at end of file diff --git a/collections/isEmpty.html b/collections/isEmpty.html index b742b6ebd..1ec02b45a 100644 --- a/collections/isEmpty.html +++ b/collections/isEmpty.html @@ -32,7 +32,7 @@ // 可以配合 filter 方法过滤掉转化布尔类型为 false 的值 collect([false, null , [],'', 0])->filter()->isEmpty();

相关方法

- + \ No newline at end of file diff --git a/collections/isNotEmpty.html b/collections/isNotEmpty.html index ad84ccce3..7da4acddc 100644 --- a/collections/isNotEmpty.html +++ b/collections/isNotEmpty.html @@ -26,7 +26,7 @@ collect([null])->isNotEmpty(); // true
collect([''])->isNotEmpty(); // true
 
 collect([null])->isNotEmpty(); // true

isNotEmpty 相反操作的方法是 isEmpty 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/join.html b/collections/join.html index 619eb9013..ea4b96ee6 100644 --- a/collections/join.html +++ b/collections/join.html @@ -26,7 +26,7 @@ collect(['a', 'b'])->join(', ', ' and '); // 'a and b' collect(['a'])->join(', ', ' and '); // 'a' collect([])->join(', ', ' and '); // ''

相关方法

- + \ No newline at end of file diff --git a/collections/keyBy.html b/collections/keyBy.html index 1c191d4a9..1744da0d0 100644 --- a/collections/keyBy.html +++ b/collections/keyBy.html @@ -58,7 +58,7 @@ "PROD-200" => ["product_id" => "prod-200", "name" => "chair"] ] */ - + \ No newline at end of file diff --git a/collections/keys.html b/collections/keys.html index 2d52ae3a2..01b403d30 100644 --- a/collections/keys.html +++ b/collections/keys.html @@ -28,7 +28,7 @@ ])->keys(); // ["prod-100", "prod-200"]

相关方法

- + \ No newline at end of file diff --git a/collections/last.html b/collections/last.html index 7172e5e26..a72f3e3f6 100644 --- a/collections/last.html +++ b/collections/last.html @@ -22,7 +22,7 @@ collect([])->last(null, 1000); // 1000
collect([1, 2, 3, 4])->last(fn ($element) => $element < 1, 1000);
 
 collect([])->last(null, 1000); // 1000

如果需要返回第一个元素可以使用first()方法。

相关方法

- + \ No newline at end of file diff --git a/collections/lazy.html b/collections/lazy.html index 929da3f4d..ea46a4dab 100644 --- a/collections/lazy.html +++ b/collections/lazy.html @@ -34,7 +34,7 @@ ->where('country', 'zh_CN') ->where('balance', '>', '100') ->count(); - + \ No newline at end of file diff --git a/collections/macro.html b/collections/macro.html index 472c93235..05b692b23 100644 --- a/collections/macro.html +++ b/collections/macro.html @@ -48,7 +48,7 @@ }); collect(['first', 'second'])->toLocale('es');

相关方法

- + \ No newline at end of file diff --git a/collections/make.html b/collections/make.html index e0ec29653..643dcede1 100644 --- a/collections/make.html +++ b/collections/make.html @@ -28,7 +28,7 @@ // 等同于使用 collect 方法 collect([1, 2, 3]); // [1, 2, 3]

相关方法

- + \ No newline at end of file diff --git a/collections/map.html b/collections/map.html index 60383eeb3..5bb0c866b 100644 --- a/collections/map.html +++ b/collections/map.html @@ -62,7 +62,7 @@ $newCollection; // [10, 20, 30, 40] $collection; // [1, 2, 3, 4]

相关方法

- + \ No newline at end of file diff --git a/collections/mapInto.html b/collections/mapInto.html index 53a13f043..25b95eca6 100644 --- a/collections/mapInto.html +++ b/collections/mapInto.html @@ -56,7 +56,7 @@ ->map(fn ($covert) => $covert->toCentimeters()) ->dump(); // [2.54, 5.08, 7.62, 10.16]

相关方法

- + \ No newline at end of file diff --git a/collections/mapSpread.html b/collections/mapSpread.html index cb5d8c3aa..3053c4b75 100644 --- a/collections/mapSpread.html +++ b/collections/mapSpread.html @@ -56,7 +56,7 @@ $newCollection = $collection->mapSpread(fn ($a, $b, $c) => $a * $b - $c); // [-1, 14, 47] $collection; // [[1, 2, 3, 0], [4, 5, 6, 1], [7, 8, 9, 2]] - + \ No newline at end of file diff --git a/collections/mapToDictionary.html b/collections/mapToDictionary.html index d4eee3d8b..895f22961 100644 --- a/collections/mapToDictionary.html +++ b/collections/mapToDictionary.html @@ -36,7 +36,7 @@ ); // ["apples" => [59, 69], "bananas" => [54, 94]]

相关方法

- + \ No newline at end of file diff --git a/collections/mapToGroups.html b/collections/mapToGroups.html index 61d3c3292..a31ed0d74 100644 --- a/collections/mapToGroups.html +++ b/collections/mapToGroups.html @@ -78,7 +78,7 @@ ["product" => "bananas", "price" => 94] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/mapWithKeys.html b/collections/mapWithKeys.html index d670a6ef2..ccb9361f5 100644 --- a/collections/mapWithKeys.html +++ b/collections/mapWithKeys.html @@ -90,7 +90,7 @@ $newCollection->dump(); // [] $collection->dd(); // [ 1, 2, 3, 4, 5]

相关方法

- + \ No newline at end of file diff --git a/collections/max.html b/collections/max.html index a7cc737e2..0d117c7b2 100644 --- a/collections/max.html +++ b/collections/max.html @@ -70,7 +70,7 @@ ->max( fn($value) => $value['price'] + $value['tax'] );

相关方法

- + \ No newline at end of file diff --git a/collections/median.html b/collections/median.html index 6069eb911..f6e71fbcc 100644 --- a/collections/median.html +++ b/collections/median.html @@ -30,7 +30,7 @@ ['price' => 20000], ['price' => 30000] ])->median('price'); // 20000 - + \ No newline at end of file diff --git a/collections/merge.html b/collections/merge.html index 4133f797e..57968da6b 100644 --- a/collections/merge.html +++ b/collections/merge.html @@ -34,7 +34,7 @@ // 相当于 push 方法 collect(['Desk', 'Chair'])->push(...['Bookcase', 'Door']);

相关方法

- + \ No newline at end of file diff --git a/collections/mergeRecursive.html b/collections/mergeRecursive.html index ee7000456..0be1013ac 100644 --- a/collections/mergeRecursive.html +++ b/collections/mergeRecursive.html @@ -42,7 +42,7 @@ "discount" => false, ] */

相关方法

- + \ No newline at end of file diff --git a/collections/min.html b/collections/min.html index 6cbec0307..afdcbdb24 100644 --- a/collections/min.html +++ b/collections/min.html @@ -68,7 +68,7 @@ ->min( fn($value) => $value['price'] + $value['tax'] );

相关方法

- + \ No newline at end of file diff --git a/collections/mode.html b/collections/mode.html index b133c726a..7c1b806b2 100644 --- a/collections/mode.html +++ b/collections/mode.html @@ -30,7 +30,7 @@ ['foo' => 40] ])->mode('foo'); // [10] - + \ No newline at end of file diff --git a/collections/nth.html b/collections/nth.html index ee1d3c60b..8c5555db3 100644 --- a/collections/nth.html +++ b/collections/nth.html @@ -36,7 +36,7 @@ $newCollection->dump(); // [2, 4] $collection->dd(); // [1, 2, 3 ,4] - + \ No newline at end of file diff --git a/collections/only.html b/collections/only.html index 596d75d9b..b603c1fc9 100644 --- a/collections/only.html +++ b/collections/only.html @@ -60,7 +60,7 @@ # 打印新集合 $newCollection->dd(); // ["product" => "coconuts", "qty" => 45]

only 相反的操作是 except 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/pad.html b/collections/pad.html index cd1731099..78cd333b2 100644 --- a/collections/pad.html +++ b/collections/pad.html @@ -32,7 +32,7 @@ collect(['A', 'B', 'C']->pad(2, 0); // ['A', 'B', 'C']

相关方法

- + \ No newline at end of file diff --git a/collections/partition.html b/collections/partition.html index d3c51dc7a..b6de64d6e 100644 --- a/collections/partition.html +++ b/collections/partition.html @@ -26,7 +26,7 @@ $underThree->dump(); // [1, 2] $equalOrAboveThree->dd(); // [3, 4, 5, 6]

相关方法

- + \ No newline at end of file diff --git a/collections/pipe.html b/collections/pipe.html index 28b13f24b..a962e1e16 100644 --- a/collections/pipe.html +++ b/collections/pipe.html @@ -32,7 +32,7 @@ # 类似于直接调用 sum 方法 collect([1, 2, 3])->sum();

相关方法

- + \ No newline at end of file diff --git a/collections/pipeInto.html b/collections/pipeInto.html index 612863531..4c19f9fdf 100644 --- a/collections/pipeInto.html +++ b/collections/pipeInto.html @@ -52,7 +52,7 @@ $collection->pipeInto(ResourceCollection::class); // [1, 2, 3]

相关方法

- + \ No newline at end of file diff --git a/collections/pipeThrough.html b/collections/pipeThrough.html index f3c7a2ede..0c9ee98cf 100644 --- a/collections/pipeThrough.html +++ b/collections/pipeThrough.html @@ -32,7 +32,7 @@ ]); // 15

相关方法

- + \ No newline at end of file diff --git a/collections/pluck.html b/collections/pluck.html index bd1116e35..fe6ed826c 100644 --- a/collections/pluck.html +++ b/collections/pluck.html @@ -86,7 +86,7 @@ ["product" => "coconuts", "price" => 80, "quantity" => 25] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/pop.html b/collections/pop.html index 1eb5d3ab3..8a28c32cd 100644 --- a/collections/pop.html +++ b/collections/pop.html @@ -28,7 +28,7 @@ # 原集合被改变 $collection->all(); // [1, 2, 3, 4]

相关方法

- + \ No newline at end of file diff --git a/collections/prepend.html b/collections/prepend.html index c3fd3bc8b..5d68d148d 100644 --- a/collections/prepend.html +++ b/collections/prepend.html @@ -34,7 +34,7 @@ $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two' => 2]

相关方法

- + \ No newline at end of file diff --git a/collections/pull.html b/collections/pull.html index 984de45e6..4fbd46d98 100644 --- a/collections/pull.html +++ b/collections/pull.html @@ -26,7 +26,7 @@ $collect->pull('name'); // 'Desk' $collect->all(); // ['product_id' => 'prod-100']

相关方法

- + \ No newline at end of file diff --git a/collections/push.html b/collections/push.html index 45ea680e8..f1936435c 100644 --- a/collections/push.html +++ b/collections/push.html @@ -26,7 +26,7 @@ $collection->push(5); $collection->all(); // [1, 2, 3, 4, 5]

相关方法

- + \ No newline at end of file diff --git a/collections/put.html b/collections/put.html index 926195cdd..0bea8935f 100644 --- a/collections/put.html +++ b/collections/put.html @@ -26,7 +26,7 @@ $collect->put('price', 100); $collect->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

相关方法

- + \ No newline at end of file diff --git a/collections/random.html b/collections/random.html index ba147b62b..40ef3660d 100644 --- a/collections/random.html +++ b/collections/random.html @@ -26,7 +26,7 @@ // [0 => 1, 1 => 2, 4 => 5] - (retrieved randomly)
collect([1, 2, 3, 4, 5])->random(3);
 
 // [0 => 1, 1 => 2, 4 => 5] - (retrieved randomly)

如果传入的值大于当前集合中的值,则会抛出 InvalidArgumentException 错误。

相关方法

- + \ No newline at end of file diff --git a/collections/reduce.html b/collections/reduce.html index 42aa97ac4..489c951e6 100644 --- a/collections/reduce.html +++ b/collections/reduce.html @@ -52,7 +52,7 @@ ])->reduce( fn(int $carry, int $value, int $key) => $carry + ($value * $ratio[$key]) ); // 4264

相关方法

- + \ No newline at end of file diff --git a/collections/reduceSpread.html b/collections/reduceSpread.html index 4c4ad0cef..4a21f7664 100644 --- a/collections/reduceSpread.html +++ b/collections/reduceSpread.html @@ -24,7 +24,7 @@ fn($carry, $item, $key) => [$carry + $item[0] + $item[1]], 0 ); // [21]

相关方法

- + \ No newline at end of file diff --git a/collections/reject.html b/collections/reject.html index ce03cb956..cf0a284f7 100644 --- a/collections/reject.html +++ b/collections/reject.html @@ -24,7 +24,7 @@ ->reject(fn ($item) => $item > 2); // [1, 2]

相关方法

- + \ No newline at end of file diff --git a/collections/replace.html b/collections/replace.html index 867cc667f..ec9750936 100644 --- a/collections/replace.html +++ b/collections/replace.html @@ -22,7 +22,7 @@ // ['Taylor', 'Victoria', 'James', 'Finn']
collect(['Taylor', 'Abigail', 'James'])->replace([1 => 'Victoria', 3 => 'Finn']);
 
 // ['Taylor', 'Victoria', 'James', 'Finn']

相关方法

- + \ No newline at end of file diff --git a/collections/replaceRecursive.html b/collections/replaceRecursive.html index be28c1020..70cf56fe9 100644 --- a/collections/replaceRecursive.html +++ b/collections/replaceRecursive.html @@ -44,7 +44,7 @@ ]); // ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

相关方法

- + \ No newline at end of file diff --git a/collections/reverse.html b/collections/reverse.html index b4b88d72e..70ea31461 100644 --- a/collections/reverse.html +++ b/collections/reverse.html @@ -42,7 +42,7 @@ ->values(); // [4, 3, 2, 1]

相关方法

- + \ No newline at end of file diff --git a/collections/search.html b/collections/search.html index 97486c0f6..a40eb79e3 100644 --- a/collections/search.html +++ b/collections/search.html @@ -22,7 +22,7 @@ ); // 2
collect([2, 4, 6, 8])->search(
     fn ($item) => $item > 5
 ); // 2

相关方法

- + \ No newline at end of file diff --git a/collections/shift.html b/collections/shift.html index e5ff261da..eeca77376 100644 --- a/collections/shift.html +++ b/collections/shift.html @@ -26,7 +26,7 @@ $collection->shift(); // 1 $collection->all(); // [2, 3, 4, 5]

相关方法

- + \ No newline at end of file diff --git a/collections/shuffle.html b/collections/shuffle.html index d71ecb52c..cb1185dab 100644 --- a/collections/shuffle.html +++ b/collections/shuffle.html @@ -22,7 +22,7 @@ // [4, 2, 5, 1, 3]
collect([1, 2, 3, 4, 5])->shuffle();
 
 // [4, 2, 5, 1, 3]

相关方法

- + \ No newline at end of file diff --git a/collections/skip.html b/collections/skip.html index 90bf6e0cc..68bf667fd 100644 --- a/collections/skip.html +++ b/collections/skip.html @@ -22,7 +22,7 @@ // [4 => 5, 5 => 6]
collect([1, 2, 3, 4, 5, 6])->skip(4);
  
 // [4 => 5, 5 => 6]

相关方法

- + \ No newline at end of file diff --git a/collections/skipUntil.html b/collections/skipUntil.html index 8c85d937a..58cb6e475 100644 --- a/collections/skipUntil.html +++ b/collections/skipUntil.html @@ -26,7 +26,7 @@ // [2 => 3, 3 => 4]
collect([1, 2, 3, 4])->skipUntil(fn($item) => $item >= 3);
 
 // [2 => 3, 3 => 4]

注意: 如果找不到给定的值,或者回调从未返回 true ,则 skipUntil 方法将返回一个空集合。

相关方法

- + \ No newline at end of file diff --git a/collections/skipWhile.html b/collections/skipWhile.html index 1e3f704ed..d4615d07b 100644 --- a/collections/skipWhile.html +++ b/collections/skipWhile.html @@ -22,7 +22,7 @@ ); // [3 => 4]
collect([1, 2, 3, 4])->skipWhile(
     fn($item) => $item <= 3
 ); // [3 => 4]

注意: 如果回调从不返回 true,则 skipWhile 方法将返回一个空集合。

php
collect([1, 2, 3, 4])->skipWhile(fn () => true); // []
collect([1, 2, 3, 4])->skipWhile(fn () => true); // []

相关方法

- + \ No newline at end of file diff --git a/collections/slice.html b/collections/slice.html index 38424b91d..dedfd0f11 100644 --- a/collections/slice.html +++ b/collections/slice.html @@ -38,7 +38,7 @@ collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ->slice(-4, 2); // [6 => 7, 7 => 8]

默认情况下,返回的内容将会保留原始键。

假如不需要保留原始的键,可以使用 values 方法来重新建立索引。

相关方法

- + \ No newline at end of file diff --git a/collections/sliding.html b/collections/sliding.html index 14f2c66c5..9aa8a9ba9 100644 --- a/collections/sliding.html +++ b/collections/sliding.html @@ -28,7 +28,7 @@ ->sliding(3, step: 2); // [[1, 2, 3], [3, 4, 5]]

相关方法

- + \ No newline at end of file diff --git a/collections/sole.html b/collections/sole.html index 9055cb72a..59ccfe461 100644 --- a/collections/sole.html +++ b/collections/sole.html @@ -40,7 +40,7 @@ ])->sole('product', 'Chair'); // ['product' => 'Chair', 'price' => 100]

相关方法

- + \ No newline at end of file diff --git a/collections/sort.html b/collections/sort.html index 10b5a8006..b362c1e54 100644 --- a/collections/sort.html +++ b/collections/sort.html @@ -36,7 +36,7 @@ ->sort(fn ($a, $b) => str_replace('-', '', $a) < $b ? -1 : 1); // [3 => "A11", 0 => "A55", 2 => "B22", 1 => "B54"]

如果有更高级的排序需求,你可以传入回调来用你自己的算法进行排序。请参阅 PHP 文档的 usort,这是集合的 sort 方法在底层所调用的。

如果要对嵌套数组或对象的集合进行排序,参考 sortBysortByDesc 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/sortBy.html b/collections/sortBy.html index a3f3576b3..996909402 100644 --- a/collections/sortBy.html +++ b/collections/sortBy.html @@ -62,7 +62,7 @@ ["product" => "bananas", "price" => 5, "code" => "A50"] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/sortByDesc.html b/collections/sortByDesc.html index f9430d4bd..49c6a9293 100644 --- a/collections/sortByDesc.html +++ b/collections/sortByDesc.html @@ -66,7 +66,7 @@ ["product" => "coconuts", "price" => 3, "code" => "A20"] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/sortDesc.html b/collections/sortDesc.html index 7ea2da210..ccdd4edc2 100644 --- a/collections/sortDesc.html +++ b/collections/sortDesc.html @@ -24,7 +24,7 @@ ->sortDesc(); // [5, 4, 3, 2, 1]

相关方法

- + \ No newline at end of file diff --git a/collections/sortKeys.html b/collections/sortKeys.html index 4d42a3fe5..fda79bfe4 100644 --- a/collections/sortKeys.html +++ b/collections/sortKeys.html @@ -22,7 +22,7 @@ // ["first" => "John", "id" => 22345, "last" => "Doe"]
collect(['id' => 22345, 'first' => 'John', 'last' => 'Doe'])->sortKeys();
 
 // ["first" => "John", "id" => 22345, "last" => "Doe"]

相关方法

- + \ No newline at end of file diff --git a/collections/sortKeysDesc.html b/collections/sortKeysDesc.html index 4aaea4a54..ffaab57d4 100644 --- a/collections/sortKeysDesc.html +++ b/collections/sortKeysDesc.html @@ -22,7 +22,7 @@ // [ "last" => "Doe", "id" => 22345, "first" => "John"]
collect(['id' => 22345, 'first' => 'John', 'last' => 'Doe'])->sortKeysDesc();
 
 // [ "last" => "Doe", "id" => 22345, "first" => "John"]

相关方法

- + \ No newline at end of file diff --git a/collections/sortKeysUsing.html b/collections/sortKeysUsing.html index 8eb014c9d..da33d8ca5 100644 --- a/collections/sortKeysUsing.html +++ b/collections/sortKeysUsing.html @@ -30,7 +30,7 @@ ])->sortKeysUsing('strnatcasecmp'); // ['first' => 'John', 'ID' => 22345, 'last' => 'Doe']

回调必须是返回小于、等于或大于零的整数的比较函数。

相关方法

- + \ No newline at end of file diff --git a/collections/splice.html b/collections/splice.html index f83638ea2..cdd11e93a 100644 --- a/collections/splice.html +++ b/collections/splice.html @@ -78,7 +78,7 @@ $collection->all(); // [1, 2, 10, 11, 4, 5]

相关方法

- + \ No newline at end of file diff --git a/collections/split.html b/collections/split.html index 0e35bca6f..4a4be3f6c 100644 --- a/collections/split.html +++ b/collections/split.html @@ -22,7 +22,7 @@ // [[1,2], [3, 4], [5]]
collect([1, 2, 3, 4, 5])->split(3);
 
 // [[1,2], [3, 4], [5]]

相关方法

- + \ No newline at end of file diff --git a/collections/splitIn.html b/collections/splitIn.html index 778c4815c..11546a9e2 100644 --- a/collections/splitIn.html +++ b/collections/splitIn.html @@ -22,7 +22,7 @@ // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->splitIn(3);
 
 // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

相关方法

- + \ No newline at end of file diff --git a/collections/sum.html b/collections/sum.html index 0b164fd93..3dd5a0e7d 100644 --- a/collections/sum.html +++ b/collections/sum.html @@ -44,7 +44,7 @@ ])->sum(fn ($product) => count($product['colors'])); // 6

相关方法

- + \ No newline at end of file diff --git a/collections/take.html b/collections/take.html index 35f31069b..a06976abd 100644 --- a/collections/take.html +++ b/collections/take.html @@ -36,7 +36,7 @@ collect([1, 2, 3, 4])->take(-2); // [3, 4]

相关方法

- + \ No newline at end of file diff --git a/collections/takeUntil.html b/collections/takeUntil.html index 74dd10c09..e259cc349 100644 --- a/collections/takeUntil.html +++ b/collections/takeUntil.html @@ -28,7 +28,7 @@ // [1, 2]
collect([1, 2, 3, 4])->takeUntil(3);
 
 // [1, 2]

注意: 如果找不到给定的值或回调从未返回 true ,则 takeUntil 方法将返回集合中的所有项目。

相关方法

- + \ No newline at end of file diff --git a/collections/takeWhile.html b/collections/takeWhile.html index d794d6118..905fa97f1 100644 --- a/collections/takeWhile.html +++ b/collections/takeWhile.html @@ -24,7 +24,7 @@ ->takeWhile(fn ($item) => $item < 3); // [1, 2]

如果回调从不返回 false,则 takeWhile 方法将返回集合中的所有项目。

相关方法

- + \ No newline at end of file diff --git a/collections/tap.html b/collections/tap.html index 9acda3b06..56a5cfe72 100644 --- a/collections/tap.html +++ b/collections/tap.html @@ -32,7 +32,7 @@ ->shift(); // 1

相关方法

- + \ No newline at end of file diff --git a/collections/times.html b/collections/times.html index b3b98c926..90187197e 100644 --- a/collections/times.html +++ b/collections/times.html @@ -26,7 +26,7 @@ collect()->times(3, fn ($number) => User::factory()->create(['name' => $number . ' Cool Name']));
use App\Models\User;
 
 collect()->times(3, fn ($number) => User::factory()->create(['name' => $number . ' Cool Name']));
- + \ No newline at end of file diff --git a/collections/toArray.html b/collections/toArray.html index 9f6b2502a..96704d842 100644 --- a/collections/toArray.html +++ b/collections/toArray.html @@ -22,7 +22,7 @@ // [['name' => 'Desk', 'price' => 200]]
collect(['name' => 'Desk', 'price' => 200])->toArray();
 
 // [['name' => 'Desk', 'price' => 200]]

toArray() 也会将所有集合的嵌套对象转换为数组。

如果获取原数组,可以使用 all 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/toJson.html b/collections/toJson.html index daf0d303e..640ddb398 100644 --- a/collections/toJson.html +++ b/collections/toJson.html @@ -32,7 +32,7 @@ ->toJson(JSON_PRETTY_PRINT); // {"product": "apples", "price": 45}

更多参数参考JSON 常量

相关方法

- + \ No newline at end of file diff --git a/collections/transform.html b/collections/transform.html index bdddb1364..4d256ec59 100644 --- a/collections/transform.html +++ b/collections/transform.html @@ -24,7 +24,7 @@ ->transform(fn ($item) => $item * 2); // [2, 4, 6, 8, 10]

与大多数集合的方法不同,transform 会修改集合本身。

如果想创建新集合,应该使用 map 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/undot.html b/collections/undot.html index 8bbd79602..5ba8e3f3f 100644 --- a/collections/undot.html +++ b/collections/undot.html @@ -66,7 +66,7 @@ ] ] */ - + \ No newline at end of file diff --git a/collections/union.html b/collections/union.html index e297d2e6f..d98fa4973 100644 --- a/collections/union.html +++ b/collections/union.html @@ -24,7 +24,7 @@ ->union([3 => ['c'], 1 => ['b']]); // [1 => ["a"],2 => ["b"],3 => ["c"]]

相关方法

- + \ No newline at end of file diff --git a/collections/unique.html b/collections/unique.html index f5dad7cc5..f0a188eb3 100644 --- a/collections/unique.html +++ b/collections/unique.html @@ -78,7 +78,7 @@ ["name" => "Galaxy Gear", "brand" => "Samsung", "type" => "watch"] ] */

在检查项目值时 unique 方法使用的是「宽松」比较,意味着具有整数值的字符串将被视为等于相同值的整数。

使用 uniqueStrict 可以进行「严格」比较 。

相关方法

- + \ No newline at end of file diff --git a/collections/uniqueStrict.html b/collections/uniqueStrict.html index 153c97db9..4f0205bbc 100644 --- a/collections/uniqueStrict.html +++ b/collections/uniqueStrict.html @@ -70,7 +70,7 @@ ["name" => "Galaxy Gear", "brand" => "Samsung", "type" => "watch"] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/unless.html b/collections/unless.html index d02f2806c..b5d3e4c7e 100644 --- a/collections/unless.html +++ b/collections/unless.html @@ -26,7 +26,7 @@ ->unless(false, fn($item) => $item->push(5)); // [1, 2, 3, 5]

如果需要反向操作,请使用 when 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/unwrap.html b/collections/unwrap.html index a41033554..1c3f84b61 100644 --- a/collections/unwrap.html +++ b/collections/unwrap.html @@ -26,7 +26,7 @@ collect()->unwrap('string'); // "string" collect()->unwrap(collect('string')); // ["string"]

相关方法

- + \ No newline at end of file diff --git a/collections/value.html b/collections/value.html index 61a39d87f..3039b3e8e 100644 --- a/collections/value.html +++ b/collections/value.html @@ -28,7 +28,7 @@ ])->value('price'); // 200

相关方法

- + \ No newline at end of file diff --git a/collections/values.html b/collections/values.html index 4c5a3a3c7..5d18c7dde 100644 --- a/collections/values.html +++ b/collections/values.html @@ -38,7 +38,7 @@ ["product" => "Desk", "price" => 200] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/when.html b/collections/when.html index d74ad06a7..e8ff9bece 100644 --- a/collections/when.html +++ b/collections/when.html @@ -26,7 +26,7 @@ ->when(false, fn ($item) => $item->push(5)); // [1, 2, 3, 4]

相关方法

- + \ No newline at end of file diff --git a/collections/whenEmpty.html b/collections/whenEmpty.html index e5ef8645d..9044a9dc4 100644 --- a/collections/whenEmpty.html +++ b/collections/whenEmpty.html @@ -40,7 +40,7 @@ fn ($item) => $item->push('Taylor') ); // ["Michael", "Tom", "Taylor"]

如果需要和 whenEmpty 方法相反的操作,可以使用 whereNotEmpty 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/whenNotEmpty.html b/collections/whenNotEmpty.html index 5810169b7..0f902df28 100644 --- a/collections/whenNotEmpty.html +++ b/collections/whenNotEmpty.html @@ -38,7 +38,7 @@ ); // ["curder"]

相关方法

- + \ No newline at end of file diff --git a/collections/where.html b/collections/where.html index 670ea76a9..1fc68e458 100644 --- a/collections/where.html +++ b/collections/where.html @@ -66,7 +66,7 @@ ["product" => "coconuts", "price" => 80], ] */

比较数值的时候,where 方法使用「宽松」比较,意味着具有整数值的字符串将被认为等于相同值的整数。

使用 whereStrict 方法来进行「严格」比较过滤。

相关方法

- + \ No newline at end of file diff --git a/collections/whereBetween.html b/collections/whereBetween.html index 7a205a27c..00f696e47 100644 --- a/collections/whereBetween.html +++ b/collections/whereBetween.html @@ -44,7 +44,7 @@ ["product" => "coconuts", "price" => 80] ] */

如果需要过滤集合的值不包含在某个范围可以使用 whereNotBetween 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/whereIn.html b/collections/whereIn.html index a56fa89ad..bef5730b3 100644 --- a/collections/whereIn.html +++ b/collections/whereIn.html @@ -44,7 +44,7 @@ ["product" => "coconuts", "price" => "80"] ] */

whereIn 方法在检查项目值时使用「宽松」比较,意味着具有整数值的字符串将被视为等于相同值的整数。

可以使用 whereInStrict 做比较 严格 的匹配。

相关方法

- + \ No newline at end of file diff --git a/collections/whereInStrict.html b/collections/whereInStrict.html index 55057fe49..adb6ee973 100644 --- a/collections/whereInStrict.html +++ b/collections/whereInStrict.html @@ -32,7 +32,7 @@ ])->whereInStrict('price', [50, 70, 80]); // []

此方法的使用和 whereIn 方法类似,只是使用了「严格」比较来匹配所有值。

相关方法

- + \ No newline at end of file diff --git a/collections/whereInstanceOf.html b/collections/whereInstanceOf.html index 96f8604c2..561f1e9d1 100644 --- a/collections/whereInstanceOf.html +++ b/collections/whereInstanceOf.html @@ -30,7 +30,7 @@ ->whereInstanceOf(Post::class); // [2 => Post]

相关方法

- + \ No newline at end of file diff --git a/collections/whereNotBetween.html b/collections/whereNotBetween.html index 6d91ccb4f..e5e7c8e3a 100644 --- a/collections/whereNotBetween.html +++ b/collections/whereNotBetween.html @@ -32,7 +32,7 @@ ])->whereNotBetween('price', [60, 100]); // [["product" => "apples", "price" => 50]]

如果需要过滤集合的值包含在某个范围可以使用 whereBetween 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/whereNotIn.html b/collections/whereNotIn.html index 87608f78d..f4e1c46f7 100644 --- a/collections/whereNotIn.html +++ b/collections/whereNotIn.html @@ -42,7 +42,7 @@ ["product" => "banners", "price" => 70] ] */

whereNotIn 方法在检查项目值时使用「宽松」比较,意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 whereNotInStrict 做比较 严格 的匹配。

相关方法

- + \ No newline at end of file diff --git a/collections/whereNotInStrict.html b/collections/whereNotInStrict.html index 949905301..ecbb682c0 100644 --- a/collections/whereNotInStrict.html +++ b/collections/whereNotInStrict.html @@ -48,7 +48,7 @@ ["product" => "coconuts", "price" => "80"] ] */

此方法的使用和 whereNotIn 方法类似,只是使用了「严格」比较来匹配所有值。

相关方法

- + \ No newline at end of file diff --git a/collections/whereNotNull.html b/collections/whereNotNull.html index 49fecd127..acf37d1cd 100644 --- a/collections/whereNotNull.html +++ b/collections/whereNotNull.html @@ -40,7 +40,7 @@ ['name' => 'Bookcase'] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/whereNull.html b/collections/whereNull.html index f52566627..4e5d27f58 100644 --- a/collections/whereNull.html +++ b/collections/whereNull.html @@ -30,7 +30,7 @@ ])->whereNull('name'); // [['name' => null]]

相关方法

- + \ No newline at end of file diff --git a/collections/whereStrict.html b/collections/whereStrict.html index 4d2d46d52..19d9f14bf 100644 --- a/collections/whereStrict.html +++ b/collections/whereStrict.html @@ -46,7 +46,7 @@ ])->whereStrict('price', '>', '50'); // []

比较数值的时候,whereStrict 方法使用「严格」比较,意味着具有整数值的字符串将被认为等于相同值的整数。

使用 where 方法来进行较为松散比较过滤。

相关方法

- + \ No newline at end of file diff --git a/collections/wrap.html b/collections/wrap.html index 9476942e3..a2f1e97db 100644 --- a/collections/wrap.html +++ b/collections/wrap.html @@ -26,7 +26,7 @@ collect()->wrap('string'); // ["string"] collect()->wrap(collect('string')); // ["string"]

相关方法

- + \ No newline at end of file diff --git a/collections/zip.html b/collections/zip.html index 9c6597dca..e3af55889 100644 --- a/collections/zip.html +++ b/collections/zip.html @@ -90,7 +90,7 @@ [4, 8, "b"] ] */ - + \ No newline at end of file diff --git a/hashmap.json b/hashmap.json index 7ea264375..db4e0a406 100644 --- a/hashmap.json +++ b/hashmap.json @@ -1 +1 @@ -{"collections_crossjoin.md":"4312c304","collections_duplicates.md":"01565b9f","collections_every.md":"f2014a96","collections_chunkwhile.md":"1fc9c43f","collections_chunk.md":"e82aef25","collections_keys.md":"e6a7eb13","collections_whereinstanceof.md":"47931cba","collections_last.md":"ac8ed937","collections_containsoneitem.md":"2813b85c","index.md":"7e15de2e","model_index.md":"65d090af","collections_replace.md":"af46b599","collections_replacerecursive.md":"be804bf4","model_laravel-model-caching.md":"31fa8c56","collections_eachspread.md":"3f157874","model_laravel-model-observers.md":"3ea33770","collections_sortbydesc.md":"6006bb06","collections_examples_using-sum-method.md":"1b3bd5d0","collections_partition.md":"ab0f0b1b","collections_slice.md":"4dd3466e","collections_first.md":"909ffb1f","collections_pipeinto.md":"c590688a","collections_sliding.md":"ba344d84","collections_sole.md":"b455eb96","collections_sortby.md":"ed96b870","collections_sortkeys.md":"5d7ef848","collections_except.md":"d67cf40e","model_relationships_09-one-of-many.md":"22866363","collections_sort.md":"b18cc2f0","collections_dump.md":"8188a6a7","collections_collapse.md":"4af04df9","collections_pull.md":"98c07d16","collections_containsstrict.md":"153267a6","collections_flatten.md":"ddbbf82a","collections_combine.md":"ab940309","collections_get.md":"9e67411b","collections_diff.md":"68b676d9","collections_push.md":"15054d10","collections_diffassocusing.md":"186605af","collections_count.md":"f02151e3","collections_countby.md":"f3b908c9","collections_has.md":"6b49117b","collections_groupby.md":"8b06a663","collections_diffusing.md":"0661bc87","collections_hasany.md":"d2c8bbd3","collections_diffkeysusing.md":"644dddf0","collections_doesntcontain.md":"30ec76ad","collections_implode.md":"bec75d36","collections_collect.md":"6e5b6bb5","collections_intersectbykeys.md":"dbe096fd","collections_isempty.md":"9f7f1bfc","collections_intersect.md":"fe9541bc","collections_all.md":"866e26e5","collections_join.md":"b4dd19ec","collections_diffkeys.md":"a3478105","collections_maptogroups.md":"7fc8647a","collections_keyby.md":"08435dd9","collections_examples_format-calculate-the-data-of-the-two-arrays.md":"617568ce","collections_maptodictionary.md":"7f886691","collections_examples_markdown-format.md":"a3da6641","model_relationships_01-has-one.md":"07acaefa","collections_dd.md":"62387442","collections_lazy.md":"f80b4015","collections_concat.md":"afa01eb8","collections_mapwithkeys.md":"bd4c3bc7","collections_map.md":"eacce7e5","collections_only.md":"6be7c1df","collections_make.md":"8315fa39","collections_examples_format-github-events-score.md":"48994faf","collections_median.md":"6ca1d99d","collections_examples_readme.md":"be90ccd4","collections_macro.md":"f5a07dff","collections_mode.md":"36ecd1af","collections_mergerecursive.md":"2f105f5e","collections_duplicatesstrict.md":"ac164891","collections_nth.md":"4eace7d1","collections_examples_order-info-summary.md":"d3788c86","collections_max.md":"6770fdd9","collections_random.md":"5d236f52","collections_merge.md":"f67d8193","collections_diffassoc.md":"add68bf5","collections_reducespread.md":"75a0c9e9","collections_reject.md":"43aad1ba","collections_contains.md":"29d5ded9","collections_reduce.md":"1da43799","collections_min.md":"6ed72427","collections_pop.md":"8fc3a51e","collections_sortkeysusing.md":"297e6acc","collections_sortkeysdesc.md":"96bfeb60","collections_splice.md":"be416a41","collections_split.md":"6347a833","collections_take.md":"48ef5392","collections_sum.md":"fe54e03d","collections_splitin.md":"017611bc","collections_takeuntil.md":"0a413c59","collections_tap.md":"56381fc0","collections_times.md":"bf6b4622","collections_toarray.md":"2b831547","collections_takewhile.md":"0d2e46b6","collections_tojson.md":"e4e8290b","collections_transform.md":"4e1ce8b8","collections_undot.md":"574a3b8d","collections_union.md":"868ac0eb","collections_uniquestrict.md":"35d11223","collections_unless.md":"7f5a4b69","collections_unique.md":"8fb47af9","collections_value.md":"71d8354a","collections_unwrap.md":"cbe4fc9d","collections_values.md":"acf28c9d","collections_when.md":"5338b63d","collections_whenempty.md":"58a9cabc","collections_where.md":"b7241e31","collections_whennotempty.md":"80aacd1f","collections_wherebetween.md":"875b229d","collections_wherein.md":"01f1df1c","collections_whereinstrict.md":"0ea113b1","collections_examples_map-format.md":"b8815a08","collections_wherenotbetween.md":"5b79a279","collections_wherenotnull.md":"adc571c3","collections_wherenull.md":"6dd76301","collections_wherestrict.md":"b14a42bf","collections_reverse.md":"5547e583","collections_wherenotinstrict.md":"798d674c","model_laravel-model-events.md":"5de4e853","model_relationships_readme.md":"01b55b6e","collections_filter.md":"40c43c32","collections_zip.md":"1939f968","collections_sortdesc.md":"0f2e6939","collections_index.md":"0ad87a2f","model_relationships_02-has-many.md":"89175356","collections_flip.md":"94d0b853","collections_firstorfail.md":"46ad744e","partials_readme.md":"ab807144","tips_reuse-the-environment-variable-value.md":"7be73538","collections_examples_get-the-corresponding-key-by-value.md":"ab6aad2b","collections_isnotempty.md":"44abd6c7","collections_avg.md":"7fcecbb3","collections_prepend.md":"8e1f9b87","collections_mapinto.md":"4949a20a","model_relationships_07-morph-one.md":"762f508b","collections_mapspread.md":"a1b0844f","collections_wrap.md":"aaf8f5fd","collections_search.md":"02e902cf","collections_shift.md":"5e6f9471","collections_shuffle.md":"0e9e6756","collections_skipuntil.md":"b0b1b7c8","collections_skipwhile.md":"31e2b2ba","collections_forget.md":"1d70b510","model_relationships_08-morph-many.md":"2f5243aa","others_readme.md":"dab90c72","collections_skip.md":"efebc296","others_laravel-import-custom-function-file.md":"0ff590c6","model_relationships_04-has-one-through.md":"cdd90633","readme.md":"3e1a4b98","model_relationships_06-belongs-to-many.md":"4b1a6cfb","collections_examples_using-reduce-create-lookup-array.md":"9a5539e4","collections_pad.md":"7219ae4f","collections_put.md":"0189de0a","model_some-tips-for-optimize-database-queries.md":"9995f137","collections_wherenotin.md":"d1c43fa0","model_relationships_03-has-one-of-many.md":"e1f10ac4","tips_readme.md":"a0a74427","collections_firstwhere.md":"5b378a38","tips_optimize-factory-database-batch-insert.md":"9d93f7ee","tests_readme.md":"051972ed","tests_unit-test-laravel-api-pest-framework.md":"6fa0fe2b","partials_validation.md":"5385cf50","partials_blade.md":"1678bdc7","model_relationships_05-has-many-through.md":"b0a3587c","collections_pluck.md":"30cc9e3e","model_relationships_10-morph-to-many.md":"81ffd71e","collections_forpage.md":"e9704592","others_laravel-create-custom-facade-test-demo.md":"41e8a121","others_using-custom-exceptions-to-write-better-and-clearer-code.md":"dcb53a6b","collections_flatmap.md":"9296349d","collections_each.md":"b148859f","collections_pipethrough.md":"e7adc06b","collections_pipe.md":"dae3c5bb","partials_model-relations.md":"79a609fd","partials_routing.md":"a3563599","partials_urls.md":"c349b34e","tips_db-models-and-eloquent.md":"6072c73a","partials_testing.md":"e6422a98","partials_model.md":"a7a95a0e"} +{"collections_containsstrict.md":"153267a6","readme.md":"64131247","collections_avg.md":"cb046321","collections_chunkwhile.md":"1fc9c43f","collections_chunk.md":"1ec3da6e","collections_concat.md":"afa01eb8","collections_collect.md":"6e5b6bb5","collections_combine.md":"ab940309","collections_all.md":"80ab9cd4","collections_examples_using-reduce-create-lookup-array.md":"303ebf67","collections_examples_using-sum-method.md":"1b3bd5d0","collections_except.md":"d67cf40e","collections_count.md":"f02151e3","collections_diffusing.md":"0661bc87","collections_examples_get-the-corresponding-key-by-value.md":"ab6aad2b","collections_examples_readme.md":"be90ccd4","collections_diff.md":"68b676d9","collections_contains.md":"5f9e2e6d","collections_every.md":"f2014a96","collections_containsoneitem.md":"2813b85c","collections_filter.md":"40c43c32","collections_eachspread.md":"3f157874","collections_dump.md":"8188a6a7","collections_duplicates.md":"01565b9f","collections_countby.md":"09a23ae5","collections_examples_order-info-summary.md":"459198e3","collections_diffassocusing.md":"186605af","collections_collapse.md":"57414593","collections_diffkeys.md":"a3478105","collections_doesntcontain.md":"30ec76ad","collections_dd.md":"62387442","collections_firstorfail.md":"46ad744e","collections_first.md":"db876798","collections_examples_format-github-events-score.md":"beda6110","collections_examples_markdown-format.md":"a3da6641","collections_diffassoc.md":"add68bf5","collections_duplicatesstrict.md":"ac164891","collections_diffkeysusing.md":"644dddf0","collections_each.md":"b148859f","collections_examples_format-calculate-the-data-of-the-two-arrays.md":"617568ce","collections_crossjoin.md":"4312c304","collections_get.md":"c4c23075","collections_groupby.md":"8b06a663","collections_forpage.md":"e9704592","collections_hasany.md":"d2c8bbd3","collections_flatmap.md":"9296349d","collections_has.md":"6b49117b","collections_implode.md":"bec75d36","collections_flatten.md":"ddbbf82a","collections_forget.md":"1d70b510","collections_flip.md":"94d0b853","collections_examples_map-format.md":"b8815a08","collections_firstwhere.md":"ca7b999c","collections_intersect.md":"fe9541bc","collections_intersectbykeys.md":"dbe096fd","collections_wherenotbetween.md":"5b79a279","collections_unless.md":"7f5a4b69","collections_whenempty.md":"58a9cabc","collections_tap.md":"56381fc0","collections_takewhile.md":"0d2e46b6","collections_when.md":"5338b63d","collections_wherebetween.md":"875b229d","collections_isempty.md":"9f7f1bfc","collections_median.md":"6ca1d99d","collections_merge.md":"f67d8193","collections_isnotempty.md":"44abd6c7","collections_values.md":"acf28c9d","collections_keyby.md":"08435dd9","collections_where.md":"b7241e31","collections_toarray.md":"2b831547","collections_pull.md":"98c07d16","collections_times.md":"bf6b4622","collections_unwrap.md":"cbe4fc9d","collections_join.md":"b4dd19ec","collections_pad.md":"7219ae4f","collections_partition.md":"ab0f0b1b","collections_make.md":"8315fa39","collections_pipeinto.md":"c590688a","collections_min.md":"6ed72427","collections_prepend.md":"8e1f9b87","collections_maptodictionary.md":"7f886691","collections_mapwithkeys.md":"bd4c3bc7","collections_push.md":"15054d10","collections_maptogroups.md":"7fc8647a","collections_reverse.md":"5547e583","collections_replacerecursive.md":"be804bf4","collections_shift.md":"5e6f9471","collections_slice.md":"4dd3466e","collections_random.md":"5d236f52","collections_reduce.md":"1da43799","collections_skip.md":"efebc296","collections_reducespread.md":"75a0c9e9","collections_skipuntil.md":"b0b1b7c8","collections_shuffle.md":"0e9e6756","collections_skipwhile.md":"31e2b2ba","collections_replace.md":"af46b599","collections_search.md":"02e902cf","collections_splitin.md":"017611bc","collections_sliding.md":"ba344d84","collections_sortkeysusing.md":"297e6acc","collections_sole.md":"b455eb96","collections_sort.md":"b18cc2f0","collections_whereinstanceof.md":"47931cba","collections_split.md":"6347a833","collections_take.md":"48ef5392","collections_sortdesc.md":"0f2e6939","collections_sortbydesc.md":"6006bb06","collections_sortkeys.md":"5d7ef848","collections_takeuntil.md":"0a413c59","collections_sum.md":"fe54e03d","collections_index.md":"0ad87a2f","collections_union.md":"868ac0eb","collections_keys.md":"e6a7eb13","collections_transform.md":"4e1ce8b8","collections_mergerecursive.md":"2f105f5e","collections_splice.md":"be416a41","model_laravel-model-observers.md":"3ea33770","collections_wherenotnull.md":"adc571c3","collections_put.md":"0189de0a","collections_wherenotinstrict.md":"798d674c","collections_undot.md":"574a3b8d","collections_wherenull.md":"6dd76301","collections_wherestrict.md":"b14a42bf","collections_reject.md":"43aad1ba","collections_mapinto.md":"4949a20a","collections_wrap.md":"aaf8f5fd","collections_zip.md":"1939f968","model_index.md":"65d090af","collections_macro.md":"f5a07dff","collections_tojson.md":"e4e8290b","model_relationships_01-has-one.md":"07acaefa","collections_lazy.md":"f80b4015","collections_sortby.md":"ed96b870","collections_unique.md":"8fb47af9","model_relationships_07-morph-one.md":"762f508b","model_laravel-model-events.md":"5de4e853","model_relationships_readme.md":"01b55b6e","others_laravel-import-custom-function-file.md":"0ff590c6","collections_wherein.md":"01f1df1c","collections_whereinstrict.md":"0ea113b1","collections_value.md":"71d8354a","collections_nth.md":"4eace7d1","collections_mode.md":"36ecd1af","collections_max.md":"6770fdd9","collections_only.md":"6be7c1df","collections_uniquestrict.md":"35d11223","index.md":"7e15de2e","collections_mapspread.md":"a1b0844f","collections_wherenotin.md":"d1c43fa0","collections_sortkeysdesc.md":"96bfeb60","collections_pipe.md":"dae3c5bb","model_laravel-model-caching.md":"31fa8c56","others_readme.md":"dab90c72","model_relationships_08-morph-many.md":"2f5243aa","collections_whennotempty.md":"80aacd1f","model_relationships_02-has-many.md":"89175356","model_relationships_06-belongs-to-many.md":"4b1a6cfb","tips_readme.md":"a0a74427","model_some-tips-for-optimize-database-queries.md":"9995f137","tips_reuse-the-environment-variable-value.md":"60398b96","tips_optimize-factory-database-batch-insert.md":"6cd4dbb4","partials_urls.md":"c349b34e","partials_model-relations.md":"50893065","collections_pipethrough.md":"e7adc06b","tests_readme.md":"051972ed","partials_readme.md":"ab807144","model_relationships_03-has-one-of-many.md":"e1f10ac4","collections_pop.md":"8fc3a51e","partials_routing.md":"a3563599","collections_map.md":"eacce7e5","collections_last.md":"ac8ed937","collections_pluck.md":"30cc9e3e","model_relationships_09-one-of-many.md":"22866363","model_relationships_05-has-many-through.md":"b0a3587c","others_using-custom-exceptions-to-write-better-and-clearer-code.md":"97ae1369","others_laravel-create-custom-facade-test-demo.md":"41e8a121","model_relationships_10-morph-to-many.md":"81ffd71e","model_relationships_04-has-one-through.md":"cdd90633","tests_unit-test-laravel-api-pest-framework.md":"6fa0fe2b","partials_validation.md":"5385cf50","tips_db-models-and-eloquent.md":"cf99938b","partials_blade.md":"c8fe88a9","partials_testing.md":"b2dcd88d","partials_model.md":"07e05036"} diff --git a/index.html b/index.html index 3959b094d..967d9521a 100644 --- a/index.html +++ b/index.html @@ -18,7 +18,7 @@
Skip to content

Laravel 学习记录

具有表现力和优雅语法的 Web 应用程序框架

- + \ No newline at end of file diff --git a/model/index.html b/model/index.html index 061ebc8c3..d21ab3f08 100644 --- a/model/index.html +++ b/model/index.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/model/laravel-model-caching.html b/model/laravel-model-caching.html index 181a4675d..322028f45 100644 --- a/model/laravel-model-caching.html +++ b/model/laravel-model-caching.html @@ -206,7 +206,7 @@ return $this->comments->toArray(); }); }

最后,我在文章模型中定义了 cachekey() 方法,但是您希望通过一个叫做 ProvidesModelCacheKey 的 trait 来定义这个方法,您可以在多个模型上使用这个方法,或者在我们所有模型扩展的基本模型上定义方法。

您甚至可能希望为实现 cachekey() 方法的模型使用合同(接口)。

- + \ No newline at end of file diff --git a/model/laravel-model-events.html b/model/laravel-model-events.html index cf5f8f629..d794f7cca 100644 --- a/model/laravel-model-events.html +++ b/model/laravel-model-events.html @@ -264,7 +264,7 @@ saving event is fired creating event is fired */

有了模型事件之后,我们就很方便地在模型创建、更新或删除的不同生命周期阶段添加相应的业务逻辑。

- + \ No newline at end of file diff --git a/model/laravel-model-observers.html b/model/laravel-model-observers.html index 31d63f317..4f8287273 100644 --- a/model/laravel-model-observers.html +++ b/model/laravel-model-observers.html @@ -282,7 +282,7 @@ updated event is fired saved event is fired */

通过执行上面的代码,我们可以看到会依次触发 savingupdatingupdatedsaved 事件。

- + \ No newline at end of file diff --git a/model/relationships/01-has-one.html b/model/relationships/01-has-one.html index 4aff6f2ab..6a9f27651 100644 --- a/model/relationships/01-has-one.html +++ b/model/relationships/01-has-one.html @@ -540,7 +540,7 @@ $this->assertInstanceOf(Relation::class, $account->user()); } } - + \ No newline at end of file diff --git a/model/relationships/02-has-many.html b/model/relationships/02-has-many.html index eee8cf693..113ac9e1d 100644 --- a/model/relationships/02-has-many.html +++ b/model/relationships/02-has-many.html @@ -598,7 +598,7 @@ $this->assertInstanceOf(Relation::class, $post->user()); } } - + \ No newline at end of file diff --git a/model/relationships/03-has-one-of-many.html b/model/relationships/03-has-one-of-many.html index 1458d6dfb..f8f482823 100644 --- a/model/relationships/03-has-one-of-many.html +++ b/model/relationships/03-has-one-of-many.html @@ -618,7 +618,7 @@ $this->assertInstanceOf(Relation::class, $order->user()); } } - + \ No newline at end of file diff --git a/model/relationships/04-has-one-through.html b/model/relationships/04-has-one-through.html index 29cc3a7de..c48379931 100644 --- a/model/relationships/04-has-one-through.html +++ b/model/relationships/04-has-one-through.html @@ -542,7 +542,7 @@ $this->assertInstanceOf(Car::class, $owner->car); $this->assertInstanceOf(Relation::class, $owner->car()); } - + \ No newline at end of file diff --git a/model/relationships/05-has-many-through.html b/model/relationships/05-has-many-through.html index 21ff84bc7..7c76a9588 100644 --- a/model/relationships/05-has-many-through.html +++ b/model/relationships/05-has-many-through.html @@ -474,7 +474,7 @@ $user->posts()->delete(); // 删除 posts 表中相关记录

通过国家关联删除文章信息

$country = \App\Country::find(1);
 $country->posts()->delete(); // 关联删除 posts 表中country_id 为 1 的相关记录,此处country_id 为 1 通过用户表关联得出。
$country = \App\Country::find(1);
 $country->posts()->delete(); // 关联删除 posts 表中country_id 为 1 的相关记录,此处country_id 为 1 通过用户表关联得出。

相关的更多的关联删除操作,可以自行尝试。

更新数据

通过关联 User 数据

- + \ No newline at end of file diff --git a/model/relationships/06-belongs-to-many.html b/model/relationships/06-belongs-to-many.html index 15a19ddd9..160b9f9de 100644 --- a/model/relationships/06-belongs-to-many.html +++ b/model/relationships/06-belongs-to-many.html @@ -690,7 +690,7 @@ $user->roles()->toggle($role); // attach 将角色附加到用户下 $user->roles()->toggle($role); // 再次执行就是 detach 效果 - + \ No newline at end of file diff --git a/model/relationships/07-morph-one.html b/model/relationships/07-morph-one.html index 455e0afd7..f1c122628 100644 --- a/model/relationships/07-morph-one.html +++ b/model/relationships/07-morph-one.html @@ -146,7 +146,7 @@ \App\User::first()->image()->save(['url' => 'new url']);

删除关联数据

$user = \App\User::first();
 $user->image->delete(); // 删除用户 users 表和 images 相关记录
$user = \App\User::first();
 $user->image->delete(); // 删除用户 users 表和 images 相关记录
- + \ No newline at end of file diff --git a/model/relationships/08-morph-many.html b/model/relationships/08-morph-many.html index 02262ca07..b77b38f55 100644 --- a/model/relationships/08-morph-many.html +++ b/model/relationships/08-morph-many.html @@ -432,7 +432,7 @@ $post->comments()->delete();

删除用户的所有评论

$user = \App\User::find(1);
 $user->comments()->delete();
$user = \App\User::find(1);
 $user->comments()->delete();

更新数据

- + \ No newline at end of file diff --git a/model/relationships/09-one-of-many.html b/model/relationships/09-one-of-many.html index fa8e280eb..ea2279d7a 100644 --- a/model/relationships/09-one-of-many.html +++ b/model/relationships/09-one-of-many.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/model/relationships/10-morph-to-many.html b/model/relationships/10-morph-to-many.html index 3aee44c03..d7eee5fe4 100644 --- a/model/relationships/10-morph-to-many.html +++ b/model/relationships/10-morph-to-many.html @@ -286,7 +286,7 @@ $tag->posts()->detach($post->id);
$tag->videos()->detach($vedio->id);
 
 $tag->posts()->detach($post->id);
- + \ No newline at end of file diff --git a/model/relationships/README.html b/model/relationships/README.html index c657529d9..2452a69a8 100644 --- a/model/relationships/README.html +++ b/model/relationships/README.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/model/some-tips-for-optimize-database-queries.html b/model/some-tips-for-optimize-database-queries.html index ffe89a83e..290e406f1 100644 --- a/model/some-tips-for-optimize-database-queries.html +++ b/model/some-tips-for-optimize-database-queries.html @@ -364,7 +364,7 @@ select * from posts order by id desc
$posts = Post::latest('id')->get();
 // or $posts = Post::orderBy('id', 'desc')->get();
 select * from posts order by id desc

原文地址

18 Tips to optimize laravel database queries

- + \ No newline at end of file diff --git a/others/README.html b/others/README.html index ecf38e262..57480104d 100644 --- a/others/README.html +++ b/others/README.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/others/laravel-create-custom-facade-test-demo.html b/others/laravel-create-custom-facade-test-demo.html index c007039ea..9230a388b 100644 --- a/others/laravel-create-custom-facade-test-demo.html +++ b/others/laravel-create-custom-facade-test-demo.html @@ -194,7 +194,7 @@ $this->assertEquals(now()->format('Y-m-d'), $result); } }

参考地址

- + \ No newline at end of file diff --git a/others/laravel-import-custom-function-file.html b/others/laravel-import-custom-function-file.html index bbe3b47ef..bbace0016 100644 --- a/others/laravel-import-custom-function-file.html +++ b/others/laravel-import-custom-function-file.html @@ -72,7 +72,7 @@ ] } }

执行自动加载

配置完毕后执行 composer dump-autoload 命令,加载配置文件。

最后,可以在项目中使用 app/Supports/helpers.php 文件中定义的函数。

- + \ No newline at end of file diff --git a/others/using-custom-exceptions-to-write-better-and-clearer-code.html b/others/using-custom-exceptions-to-write-better-and-clearer-code.html index 264d7afae..9664caa71 100644 --- a/others/using-custom-exceptions-to-write-better-and-clearer-code.html +++ b/others/using-custom-exceptions-to-write-better-and-clearer-code.html @@ -11,7 +11,7 @@ - + @@ -81,7 +81,7 @@ 'message' => 'Ticket purchased successfully.', ]); } -}

此时可以将上面的代码使用自定义异常来编写,如下所示:

php
<?php
+}

此时可以将上面的代码使用自定义异常来编写,如下所示:

php
<?php
 
 namespace App\Http\Controllers;
 
@@ -270,7 +270,7 @@
         ]);
     }
 }

相关代码仓库测试逻辑在这里:tests/Feature/CheckoutControllerTest.php

- + \ No newline at end of file diff --git a/partials/README.html b/partials/README.html index 91a2488b3..db6622824 100644 --- a/partials/README.html +++ b/partials/README.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/partials/blade.html b/partials/blade.html index 3a7f4a950..207edc3a2 100644 --- a/partials/blade.html +++ b/partials/blade.html @@ -11,7 +11,7 @@ - + @@ -41,7 +41,7 @@ // Load the view }
if (view()->exists('custom.page')) {
  // Load the view
-}

甚至可以加载一组视图,并且只会实际加载第一个存在的视图。

php
return view()->first(['custom.dashboard', 'dashboard'], $data);
return view()->first(['custom.dashboard', 'dashboard'], $data);

自定义错误页面

如果想为某些 HTTP 代码创建一个特定的错误页面,例如 500403 - 只需在 resources/views/errors/500.blade.phpresources/views/errors/403.blade.php 等中创建一个将此代码作为文件名的 blade 文件。

当出现该错误代码,它将自动加载。

官方文档 查看更多。

没有控制器的视图

如果希望路由仅显示某个视图,不用创建 Controller 方法,只需使用 Route::view() 函数。

php
Route::view('about', 'pages.about'); // 视图在 `resources/pages/about.blade.php`
Route::view('about', 'pages.about'); // 视图在 `resources/pages/about.blade.php`
php
// 1. 路由定义
+}

甚至可以加载一组视图,并且只会实际加载第一个存在的视图。

php
return view()->first(['custom.dashboard', 'dashboard'], $data);
return view()->first(['custom.dashboard', 'dashboard'], $data);

自定义错误页面

如果想为某些 HTTP 代码创建一个特定的错误页面,例如 500403 - 只需在 resources/views/errors/500.blade.phpresources/views/errors/403.blade.php 等中创建一个将此代码作为文件名的 blade 文件。

当出现该错误代码,它将自动加载。

官方文档 查看更多。

没有控制器的视图

如果希望路由仅显示某个视图,不用创建 Controller 方法,只需使用 Route::view() 函数。

php
Route::view('about', 'pages.about'); // 视图在 `resources/pages/about.blade.php`
Route::view('about', 'pages.about'); // 视图在 `resources/pages/about.blade.php`
php
// 1. 路由定义
 Route::get('about', [\App\Https\Controllers\PagesController::class, 'about']);
 
 // 2. 控制器
@@ -61,7 +61,7 @@
     {
         return view('pages.about'); // 视图在 `resources/pages/about.blade.php`
     }
-}

@auth 模版指令

使用 @auth 指令代替 @if 语句来检查登录用户。

php
@if(auth()->user())
+}

@auth 模版指令

使用 @auth 指令代替 @if 语句来检查登录用户。

php
@if(auth()->user())
 // 用户已验证身份
 @endif
@if(auth()->user())
 // 用户已验证身份
@@ -129,11 +129,11 @@
 
 @unlessenabled('regular-registration')
 // 该应用程序不接受常规注册
-@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

如果不确定模版文件是否真的存在,可以使用这些条件命令:

php
@includeIf('partials.header')
@includeIf('partials.header')
php
// 将仅为角色 ID 为 1 的用户加载对应模版 `partials.header`
+@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

如果不确定模版文件是否真的存在,可以使用这些条件命令:

php
@includeIf('partials.header')
@includeIf('partials.header')
php
// 将仅为角色 ID 为 1 的用户加载对应模版 `partials.header`
 @includeWhen(auth()->user()->role_id == 1, 'partials.header')
// 将仅为角色 ID 为 1 的用户加载对应模版 `partials.header`
 @includeWhen(auth()->user()->role_id == 1, 'partials.header')
php
// 尝试加载 `adminlte.header`,如果不存在,将加载 `default.header`
 @includeFirst('adminlte.header', 'default.header')
// 尝试加载 `adminlte.header`,如果不存在,将加载 `default.header`
-@includeFirst('adminlte.header', 'default.header')

使用 Blade-X 变量绑定来节省更多空间

php
@include("components.post", ["title" => $post->title])
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
+@includeFirst('adminlte.header', 'default.header')

使用 Blade-X 变量绑定来节省更多空间

php
@include("components.post", ["title" => $post->title])
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
 <x-post link="{{ $post->title }}"/>
 
 <!--使用 Blade-X 绑定变量-->
@@ -197,7 +197,7 @@
 <x-navbar :title="$title"/>
 
 // 从 Laravel 9.32 开始可用
-<x-navbar :$title />

自动高亮导航链接

当精确的 URL 匹配时自动高亮显示导航链接,或者传递路径或路由名称,带有请求和 CSS 类的模版组件使得显示活动/非活动状态变得简单。

php
// 在模版中使用
+<x-navbar :$title />

自动高亮导航链接

当精确的 URL 匹配时自动高亮显示导航链接,或者传递路径或路由名称,带有请求和 CSS 类的模版组件使得显示活动/非活动状态变得简单。

php
// 在模版中使用
 <x-nav-link :href="route('projects.index')">Projects</x-nav-link>
 <x-nav-link :href="route('projects.index')" active="projects.*">Projects</x-nav-link>
 <x-nav-link :href="route('projects.index')" active="projects/*">Projects</x-nav-link>
@@ -277,7 +277,7 @@
 </a>
// resources/views/components/nav-link.blade.php
 <a href="{{ $href }}" {{ $attributes->class($class) }}>
     {{ $slot }}
-</a>

@each 循环

php
// 1. 定义公共模版 resources/views/partials/item.blade.php
+</a>

@each 循环

php
// 1. 定义公共模版 resources/views/partials/item.blade.php
 <div>
     <p>Name: {{ $item->name }}
     <p>Price: {{ $item->price }}
@@ -309,7 +309,7 @@
 </div>
 
 // 2. 使用
-@each('partials.item', $items, 'item')

整理模版的简单方法

php
// if/loop 组合
+@each('partials.item', $items, 'item')

整理模版的简单方法

php
// if/loop 组合
 @if ($orders->count())
     @foreach($orders as $order)
         <div>
@@ -361,11 +361,11 @@
 
 @env(['staging', 'production'])
 // 测试环境或生产环境
-@endenv

@checked 指令

在 Laravel 9 中,可以使用 @checked 指令来选择 HTML 元素。

php
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
+@endenv

@checked 指令

在 Laravel 9 中,可以使用 @checked 指令来选择 HTML 元素。

php
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
 <input type="radio" name="active" value="0" @checked(!old('active', $user->active))/>
<input type="radio" name="active" value="1" @checked(old('active', $user->active))/>
 <input type="radio" name="active" value="0" @checked(!old('active', $user->active))/>
php
<input type="radio" name="active" value="1" {{ old('active', $user->active) ? 'checked' : '' }}/>
 <input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>
<input type="radio" name="active" value="1" {{ old('active', $user->active) ? 'checked' : '' }}/>
-<input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>

@selected 指令

在 Laravel 9 中,可以使用 @selected 指令来选择 HTML 元素。

php
<select name="country">
+<input type="radio" name="active" value="0" {{ old('active', $user->active) ? '' : 'checked' }}/>

@selected 指令

在 Laravel 9 中,可以使用 @selected 指令来选择 HTML 元素。

php
<select name="country">
     <option value="India" @selected(old('country') ?? $country == 'India')>India</option>
     <option value="Pakistan" @selected(old('country') ?? $country == 'Pakistan')>Pakistan</option>
 </select>
<select name="country">
@@ -394,7 +394,7 @@
         }
     }
 }
- + \ No newline at end of file diff --git a/partials/model-relations.html b/partials/model-relations.html index 53622bd4d..89da0c68d 100644 --- a/partials/model-relations.html +++ b/partials/model-relations.html @@ -11,7 +11,7 @@ - + @@ -147,8 +147,24 @@ $users = Book::with('author.country:id,name')->get();
// Book -> belongsTo(Author::class)
 // Author -> belongsTo(Country::class)
 
-$users = Book::with('author.country:id,name')->get();
- +$users = Book::with('author.country:id,name')->get();

更新父级

如果正在更新记录并想要更新 belongsTo 关系的 updated_at 列。

例如,添加新的帖子评论并希望 posts.updated_at 更新,只需要在 Comment 模型上定义 $touches 属性。

php
class Comment extends Model
+{
+    protected $touches = ['post'];
+
+    public function post()
+    {
+        return $this->belongsTo(Post::class); 
+    }
+}
class Comment extends Model
+{
+    protected $touches = ['post'];
+
+    public function post()
+    {
+        return $this->belongsTo(Post::class); 
+    }
+}
+ \ No newline at end of file diff --git a/partials/model.html b/partials/model.html index d997b58d6..1877f7121 100644 --- a/partials/model.html +++ b/partials/model.html @@ -11,7 +11,7 @@ - + @@ -551,7 +551,7 @@ ]), 25);
return User::orderBy('name')->chunkMap(fn ($user) => [
     'id' => $user->id,
     'name' => $user->name,
-]), 25);

更新模型但不触发事件

有时需要在不发送任何事件的情况下更新模型。现在可以使用 updateQuietly() 方法来做到这一点,该方法在背后使用 saveQuietly() 方法。

php
$flight->updateQuietly(['departed' => false]);
$flight->updateQuietly(['departed' => false]);

定期清理过时记录中的模型

有了这个特性,Laravel会自动执行此操作,只需要在 Kernel 类中调整 model:prune 命令的频率即可。

php
use Illuminate\Database\Eloquent\Model;
+]), 25);

更新模型但不触发事件

有时需要在不发送任何事件的情况下更新模型。现在可以使用 updateQuietly() 方法来做到这一点,该方法在背后使用 saveQuietly() 方法。

php
$flight->updateQuietly(['departed' => false]);
$flight->updateQuietly(['departed' => false]);

定期清理过时记录中的模型

有了这个特性,Laravel会自动执行此操作,只需要在 Kernel 类中调整 model:prune 命令的频率即可。

php
use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Prunable;
 class Flight extends Model
 {
@@ -837,7 +837,7 @@
     return new Attribute(
         get: fn ($value) => strtoupper($value),
         set: fn ($value) => strtolower($value),
-}

自定义访问/修改器

如果要在许多模型中使用相同的访问器和修改器,可以使用自定义强制转换。

只需创建一个实现 CastsAttributes 接口的类,该类应该有两个方法,第一个是 get 指定如何从数据库检索模型,第二个是 set 指定如何将值存储在数据库中。

php
// 在模型类中使用强制转换
+}

自定义访问/修改器

如果要在许多模型中使用相同的访问器和修改器,可以使用自定义强制转换。

只需创建一个实现 CastsAttributes 接口的类,该类应该有两个方法,第一个是 get 指定如何从数据库检索模型,第二个是 set 指定如何将值存储在数据库中。

php
// 在模型类中使用强制转换
 
 class User extends Authenticatable
 {
@@ -901,7 +901,7 @@
             // You can perform any action here
         });

直接将日期转换为人类可读的格式

可以使用 diffForHumans() 方法直接将 created_atupdated_at 日期转换为人类可读的格式。

例如:1分钟前、1个月前。Laravel 模型默认在 created_atupdated_at 字段上启用 Carbon 实例。

php
$post = Post::whereId($id)->first();
 $post->created_at->diffForHumans();
$post = Post::whereId($id)->first();
-$post->created_at->diffForHumans();

通过模型访问器进行排序

不是按数据库级别的访问器进行排序,而是按返回的 Collection 的访问器进行排序。

php
class User extends Model
+$post->created_at->diffForHumans();

通过模型访问器进行排序

不是按数据库级别的访问器进行排序,而是按返回的 Collection 的访问器进行排序。

php
class User extends Model
 {
     // ...
     protected $appends = ['full_name'];
@@ -975,7 +975,7 @@
     // 用户已存在并从数据库中获取
 }

数据库驱动程序 Laravel Scout

使用 Laravel9 及以上版本的 Laravel,可以将 Laravel Scout(搜索)与数据库驱动程序一起使用。

php
Company::search(request()->get('search'))->paginate(15);
Company::search(request()->get('search'))->paginate(15);

使用查询生成器上的 value 方法

当只需要查询单个列时,请使用查询生成器上的 value 方法来执行更有效的查询。

php
Statistic::where('user_id', 4)->first()->post_count; 
 Statistic::where('user_id', 4)->value('post_count');  
Statistic::where('user_id', 4)->first()->post_count; 
-Statistic::where('user_id', 4)->value('post_count');  

将数组传递给 where 方法

在使用模型查询数据时,允许将数组传递给 where 方法。

php
// You can pass an array
+Statistic::where('user_id', 4)->value('post_count');  

将数组传递给 where 方法

在使用模型查询数据时,允许将数组传递给 where 方法。

php
// You can pass an array
 JobPost::where([
     'company' => 'laravel',
     'job_type' => 'full time'
@@ -1125,7 +1125,7 @@
 $category = Category::firstOrCreate(
     ['name' => $request->name],
     ['slug' => Str::slug($request->name)]
-);

保存模型及其所有关系

使用 push() 方法更新数据库中的主模型和相关模型。

php
$user = \App\Models\User::first();
+);

保存模型及其所有关系

使用 push() 方法更新数据库中的主模型和相关模型。

php
$user = \App\Models\User::first();
 $user->name = "John";
 $user->phone->number = '1234567890';
 $user->push(); // 更新数据库中的用户表中的记录和用户关联表中的电话号码记录
$user = \App\Models\User::first();
@@ -1196,7 +1196,7 @@
         }
     }
 }
- + \ No newline at end of file diff --git a/partials/routing.html b/partials/routing.html index c176bb0ae..4162f04f3 100644 --- a/partials/routing.html +++ b/partials/routing.html @@ -474,7 +474,7 @@ * The $portfolio will be the result of the query defined in the RouteServiceProvider */ })
- + \ No newline at end of file diff --git a/partials/testing.html b/partials/testing.html index 0961ee9a0..bf6602290 100644 --- a/partials/testing.html +++ b/partials/testing.html @@ -11,7 +11,7 @@ - + @@ -45,7 +45,7 @@ $firstProduct->title, $secondProduct->title, ]); -});

在这里,确保在页面上看到我们的产品名,如果从数据库加载产品并确保显示它们,这非常有用。

在这里你也可以更具体的添加对限定条件进行测试,比如当你只想展示 released 产品时。

php
it('lists released products', function () {
+});

在这里,确保在页面上看到我们的产品名,如果从数据库加载产品并确保显示它们,这非常有用。

在这里你也可以更具体的添加对限定条件进行测试,比如当你只想展示 released 产品时。

php
it('lists released products', function () {
     // Arrange
     $releasedProduct = Product::factory()
         ->released() 
@@ -87,7 +87,7 @@
     $this->get('/')
         ->assertOk()
         ->assertViewIs('index'); 
-});

可以更进一步并测试传递到视图的数据。

php
it('returns correct view', function() {
+});

可以更进一步并测试传递到视图的数据。

php
it('returns correct view', function() {
     // Act & Assert
     $this->get('/')
         ->assertOk()
@@ -161,7 +161,7 @@
                 'description' => $anotherProduct->description,
             ],
         ]);
-});

可以在官网了解更多有关测试页面响应的信息。

数据库 Database

一般情况会将数据存储在数据库中,因此希望确保数据存储正确。

这就是 Laravel 可以通过一些断言助手来提供帮助。

php
// 该示例确保 post 请求成功并将数据正确的存储在数据库中。
+});

可以在官网了解更多有关测试页面响应的信息。

数据库 Database

一般情况会将数据存储在数据库中,因此希望确保数据存储正确。

这就是 Laravel 可以通过一些断言助手来提供帮助。

php
// 该示例确保 post 请求成功并将数据正确的存储在数据库中。
 it('stores a product', function () {
     // Act
     $this->actingAs(User::factory()->create())
@@ -213,7 +213,7 @@
 
      // use directly assertModelMissing
      $this->assertModelMissing($task);
-});

可以在官网了解有关测试数据库的更多信息。

验证 Validation

Http请求

验证是许多应用程序的关键部分。在处理请求时候需要确保只能提交满足规则的数据。

默认情况下,Laravel 会将验证错误发送回用户,可以使用 assertInvalid 方法进行检查。

php
it('requires the title', function () {
+});

可以在官网了解有关测试数据库的更多信息。

验证 Validation

Http请求

验证是许多应用程序的关键部分。在处理请求时候需要确保只能提交满足规则的数据。

默认情况下,Laravel 会将验证错误发送回用户,可以使用 assertInvalid 方法进行检查。

php
it('requires the title', function () {
     // Act
     $this->actingAs(User::factory()->create())
         ->post('product', [
@@ -255,7 +255,7 @@
 })->with([
     'title required' => [['description' => 'text'], ['title' => 'required']],
     'description required' => [['title' => 'Title'], ['description' => 'required']],
-]);

可以在官网了解更多有关测试页面响应的信息。

自定义规则

可以安装spatie/pest-expectations扩展辅助验证。

php
it('has valid phone number for chinesePhoneNumber rule',
+]);

可以在官网了解更多有关测试页面响应的信息。

自定义规则

可以安装spatie/pest-expectations扩展辅助验证。

php
it('has valid phone number for chinesePhoneNumber rule',
     fn ($value) => expect(new ChinesePhoneNumberRule())->toPassWith($value)
 )->with([
     [13800138000],
@@ -329,7 +329,7 @@
     expect($products)
         ->toBeInstanceOf(Collection::class)
         ->first()->toBeInstanceOf(Product::class);
-});

如果需要测试模型的 released() 访问的逻辑,可以如下进行相应测试:

php
it('only returns released courses for query scope', function () {
+});

如果需要测试模型的 released() 访问的逻辑,可以如下进行相应测试:

php
it('only returns released courses for query scope', function () {
     // Arrange
     Course::factory()->released()->create();
     Course::factory()->create();
@@ -353,7 +353,7 @@
 }
// App\Models\Course.php
 public function scopeReleased($query) {
     return $query->where('released_at', '>=', now());
-}

另一个模型访问器的例子:

php
it('capitalizes the first character of the first name', function () {
+}

另一个模型访问器的例子:

php
it('capitalizes the first character of the first name', function () {
     // Arrange
     $user = User::factory()->create(['first_name' => 'christoph'])
 
@@ -379,7 +379,7 @@
     return Attribute::make(
         get: fn (string $value) => ucfirst($value),
     );
-}

邮件 Mail

邮件发送

在控制器代码逻辑处理时,将发送一封电子邮件。在测试中,可以通过发送请求并确保这封电子邮件已被发送。

php
it('sends email to podcast author', function() {
+}

邮件 Mail

邮件发送

在控制器代码逻辑处理时,将发送一封电子邮件。在测试中,可以通过发送请求并确保这封电子邮件已被发送。

php
it('sends email to podcast author', function() {
     // Arrange
     Mail::fake(); 
     $podcast = Podcast::factory()->create();
@@ -515,7 +515,7 @@
     Notification::assertSentTo(
         [$user], NewProductNotification::class
     );
-});

在上面的示例中测试了创建新产品时发送通知给用户。使用 artisan 方法来触发通知。

同样,通知 Notification::fake() 伪造它,确保没有发送实际的通知。

可以在官网了解更多有关测试通知的信息。

Actions

Action 只是具有一项特定工作的简单类,它是组织代码并将逻辑与控制器分开以保持它们干净的好方法。更多详情可以看Laravel Actions扩展。

php
// controller
+});

在上面的示例中测试了创建新产品时发送通知给用户。使用 artisan 方法来触发通知。

同样,通知 Notification::fake() 伪造它,确保没有发送实际的通知。

可以在官网了解更多有关测试通知的信息。

Actions

Action 只是具有一项特定工作的简单类,它是组织代码并将逻辑与控制器分开以保持它们干净的好方法。更多详情可以看Laravel Actions扩展。

php
// controller
 class PurchaseController extends Controller
 {
     public function __invoke(User $user, Product $product): void
@@ -591,7 +591,7 @@
     expect($user->products)
         ->toHaveCount(1)
         ->first()->id->toEqual($product->id);
-});

命令 Commands

可以通过直接触发命令来进行测试。

php
it('merges two accounts', function () {
+});

命令 Commands

可以通过直接触发命令来进行测试。

php
it('merges two accounts', function () {
     // Arrange
     $user = User::factory()->create();
     $userToBeMerged = User::factory()->create();
@@ -649,7 +649,7 @@
         ->expectsQuestion('Please provide the user ID of the user you want to merge', $userToBeMerged->id)
         ->expectsOutput('Accounts merged successfully')
         ->assertSuccessful(); // 可以期待输出并确保命令成功,这意味着退出代码为 0。
-});

可以在官网了解更多有关测试命令的信息。

中间件 Middlewares

这里以一个路由中间件作为示例。源代码查看

php
<?php
+});

可以在官网了解更多有关测试命令的信息。

中间件 Middlewares

这里以一个路由中间件作为示例。源代码查看

php
<?php
 // tests/Unit/Http/Middleware/RedirectMiddlewareTest.php
 
 use App\Models\Redirect;
@@ -1013,7 +1013,7 @@
         'userId' => 1,
         'userToBeMergedId' => 2,
     ]);
-})->throws(ModelNotFoundException::class);

可以使用 Pestthrows 方法确保抛出异常。

单元测试 Unit Tests

单元测试非常适合测试小段代码,例如单个方法。

不涉及其他依赖项。这使得它们非常快速且易于编写。

php
it('creates UserData object from paddle webhook call', function () {
+})->throws(ModelNotFoundException::class);

可以使用 Pestthrows 方法确保抛出异常。

单元测试 Unit Tests

单元测试非常适合测试小段代码,例如单个方法。

不涉及其他依赖项。这使得它们非常快速且易于编写。

php
it('creates UserData object from paddle webhook call', function () {
     // Arrange
     $payload = [
       'client_email' => 'test@test.com',
@@ -1141,7 +1141,7 @@
         return $request->url() === 'https://christoph-rumpel.com/import'
             && $request['accessToken'] === 'faker-token';
     });
-});

可以在官网了解更多有关测试伪造 HTTP 调用的信息。

模拟依赖关系 mock

当使用具有依赖关系的代码时,模拟它们会很有帮助,这将使您专注于代码的逻辑而不是依赖项。

这也意味着模拟对于任何类型的测试都很有用。

在测试中希望重点测试是否发送了正确的电子邮件。

php
it('sends payment successful mail', function () {
+});

可以在官网了解更多有关测试伪造 HTTP 调用的信息。

模拟依赖关系 mock

当使用具有依赖关系的代码时,模拟它们会很有帮助,这将使您专注于代码的逻辑而不是依赖项。

这也意味着模拟对于任何类型的测试都很有用。

在测试中希望重点测试是否发送了正确的电子邮件。

php
it('sends payment successful mail', function () {
     // Arrange
     Mail::fake();
 
@@ -1189,7 +1189,7 @@
     ->expect(['dd', 'dump'])
     ->not->toBeUsed();
test('no forgotten debug statements')
     ->expect(['dd', 'dump'])
-    ->not->toBeUsed();

还可以定义更多规则。在官方文档中阅读有关它们的更多信息。

还可以参考 cachethq/core 仓库的测试代码风格。

定时任务 Schedules

断言定时任务一定会按照指定的规则执行。

php
<?php
+    ->not->toBeUsed();

还可以定义更多规则。在官方文档中阅读有关它们的更多信息。

还可以参考 cachethq/core 仓库的测试代码风格。

定时任务 Schedules

断言定时任务一定会按照指定的规则执行。

php
<?php
 // App\Console\Kernel
 
 // ...
@@ -1242,7 +1242,7 @@
 })->with([
     'check api token command is scheduled at 10 am' => ['check:api_token', '0 10 * * *'],
 ]);

其他的简单测试示例代码 curder/laravel-console-command-test-demo

相关阅读

- + \ No newline at end of file diff --git a/partials/urls.html b/partials/urls.html index 51454cacb..2797103e4 100644 --- a/partials/urls.html +++ b/partials/urls.html @@ -72,7 +72,7 @@ // account 有默认值的情况下不需要提供 <a href="{{ route('users.index')}}">Users</a>

更多官方文档查看这里

- + \ No newline at end of file diff --git a/partials/validation.html b/partials/validation.html index 1a21e9ee7..dbafcb889 100644 --- a/partials/validation.html +++ b/partials/validation.html @@ -428,7 +428,7 @@ 'prices.*.amount.required' => 'Please provide an amount for price #:position' } }

更多错误消息索引和位置可以查看官网说明。

- + \ No newline at end of file diff --git a/tests/README.html b/tests/README.html index e51c4f746..ea9331caf 100644 --- a/tests/README.html +++ b/tests/README.html @@ -18,7 +18,7 @@
- + \ No newline at end of file diff --git a/tests/unit-test-laravel-api-pest-framework.html b/tests/unit-test-laravel-api-pest-framework.html index f6aa436a2..e5f1fdc5c 100644 --- a/tests/unit-test-laravel-api-pest-framework.html +++ b/tests/unit-test-laravel-api-pest-framework.html @@ -482,7 +482,7 @@ Route::post('/todos', [TodoController::class, 'create']); Route::put('/todos/{todo}', [TodoController::class, 'update']); Route::delete('/todos/{todo}', [TodoController::class, 'delete']);

现在已经为测试提供了所有相应的实现,可以返回运行测试,它们现在都应该通过了。使用以下命令再次运行测试:

bash
./vendor/bin/pest --filter TodoTest
./vendor/bin/pest --filter TodoTest

Run pest test passed

结论

在本文中,已经了解了如何使用 Pest 测试框架为 Laravel 应用程序编写单元测试。

本教程可以作为 Pest 入门以及对 Laravel 应用程序进行单元测试的理想指南。

包含此项目完整代码 GitHub 仓库地址

原文链接

- + \ No newline at end of file diff --git a/tips/README.html b/tips/README.html index b80856e90..4be0c4f03 100644 --- a/tips/README.html +++ b/tips/README.html @@ -18,7 +18,7 @@
Skip to content
- + \ No newline at end of file diff --git a/tips/db-models-and-eloquent.html b/tips/db-models-and-eloquent.html index 6dc6749d4..ed1bfa7b9 100644 --- a/tips/db-models-and-eloquent.html +++ b/tips/db-models-and-eloquent.html @@ -11,7 +11,7 @@ - + @@ -75,7 +75,7 @@ ->rawValue('YEAR(`date_at`)'); $fullname = UserModel::where('id', $id) - ->rawValue('CONCAT(`first_name`, " ", `last_name`)');

scope 其他关系的模型范围

可以使用模型范围来定义一个相关的模型关联关系。

php
public function lessons(): HasMany
+     ->rawValue('CONCAT(`first_name`, " ", `last_name`)');

scope 其他关系的模型范围

可以使用模型范围来定义一个相关的模型关联关系。

php
public function lessons(): HasMany
 {
     return $this->hasMany(Lesson::class);
 }
@@ -97,7 +97,7 @@
 }
public function scopePublished($query)
 {
     return $query->where('is_published', true);
-}

多个查询范围

可以在 Eloquent 查询中使用多个范围。

php
User::registeredWithinDays(30)->active()->get();
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
+}

多个查询范围

可以在 Eloquent 查询中使用多个范围。

php
User::registeredWithinDays(30)->active()->get();
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
     return $query->where('active', 1);
 }
  
@@ -117,7 +117,7 @@
     DB::table('users')->update(['votes' => 1]);
  
     DB::table('posts')->delete();
-});

DB::afterCommit 事务处理

使用 DB::afterCommit() 方法,可以编写仅在事务提交时执行的代码,以及在事务回滚时丢弃的代码。

如果没有事务时,代码会立即执行。

php
class User extends Model
+});

DB::afterCommit 事务处理

使用 DB::afterCommit() 方法,可以编写仅在事务提交时执行的代码,以及在事务回滚时丢弃的代码。

如果没有事务时,代码会立即执行。

php
class User extends Model
 {
     protected static function booted()
     {
@@ -171,7 +171,7 @@
 $allMedia = $videos->merge($images);
 
 // 在 Eloquent 集合中调用 `toBase()` 以使用基本合并方法
-$allMedia = $videos->toBase()->merge($images);

在 MySQL 上使用 Laravel 进行全文搜索

php
Schema::create('comments', function (Blueprint $table) {
+$allMedia = $videos->toBase()->merge($images);

在 MySQL 上使用 Laravel 进行全文搜索

php
Schema::create('comments', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->text('description');
@@ -251,7 +251,7 @@
 {
     const CREATED_AT = 'create_time';
     const UPDATED_AT = 'update_time';
-}

更改 created_at 和 updated_at 的格式

可以在模型中添加一个方法,如下所示

php
protected function createdAtFormatted(): Attribute
+}

更改 created_at 和 updated_at 的格式

可以在模型中添加一个方法,如下所示

php
protected function createdAtFormatted(): Attribute
 {
     return Attribute::make(
         get: fn ($value, $attributes) => $attributes['created_at']->format('Y-m-d H:i:s'),
@@ -349,7 +349,7 @@
     fn ($item) => $item->name[0]
 );
Company::all()->groupBy(
     fn ($item) => $item->name[0]
-);

从不更新列

如果有一个数据库列,只想设置一次并且不再更新,可以使用 mutator 对模型设置。

php
use Illuminate\Database\Eloquent\Casts\Attribute;
+);

从不更新列

如果有一个数据库列,只想设置一次并且不再更新,可以使用 mutator 对模型设置。

php
use Illuminate\Database\Eloquent\Casts\Attribute;
  
 class User extends Model
 {
@@ -411,7 +411,7 @@
 });
Schema::create('users', function (Blueprint $table) {
     // $table->increments('id');
     $table->uuid('id')->unique();
-});
php
use Illuminate\Database\Eloquent\Concerns\HasUuids;
+});
php
use Illuminate\Database\Eloquent\Concerns\HasUuids;
 use Illuminate\Database\Eloquent\Model;
  
 class Article extends Model
@@ -529,7 +529,7 @@
 
 DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');
DB::statement('DROP TABLE users');
 
-DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

updateOrCreate 更新或创建

需要检查记录是否存在,然后更新它,或者创建一条新记录。

php
Flight::updateOrCreate(
+DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

updateOrCreate 更新或创建

需要检查记录是否存在,然后更新它,或者创建一条新记录。

php
Flight::updateOrCreate(
     ['departure' => 'Oakland', 'destination' => 'San Diego'],
     ['price' => 99, 'discounted' => 1]
 );
Flight::updateOrCreate(
@@ -861,7 +861,7 @@
     Book::query()
         ->withAvg('ratings as average_rating', 'rating')
         ->orderByDesc('average_rating');
-}

返回事务结果

如果有一个数据库事务并希望返回其结果:

php
$invoice = DB::transaction(function () {
+}

返回事务结果

如果有一个数据库事务并希望返回其结果:

php
$invoice = DB::transaction(function () {
     $invoice = Invoice::create(...);
     $invoice->items()->attach(...);
  
@@ -946,7 +946,7 @@
         get: fn($value) => bcrypt(gzuncompress($value)),
     )->shouldCache();
 }
- + \ No newline at end of file diff --git a/tips/optimize-factory-database-batch-insert.html b/tips/optimize-factory-database-batch-insert.html index 47f6dc8d6..4296f8092 100644 --- a/tips/optimize-factory-database-batch-insert.html +++ b/tips/optimize-factory-database-batch-insert.html @@ -11,13 +11,13 @@ - + -
Skip to content

优化 Factory 数据库批量插入

在创建测试数据时,使用批量插入数据库记录,而不是在单独的插入每一行,因为这将使您的测试更快。

php
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
+    
Skip to content

优化 Factory 数据库批量插入

在创建测试数据时,使用批量插入数据库记录,而不是在单独的插入每一行,因为这将使您的测试更快。

php
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
 Post::factory()->count(1000)->create();
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
 Post::factory()->count(1000)->create();
php
Post::query()->insert(
     Post::factory()->count(1000)->make()->toArray()
@@ -44,7 +44,7 @@
     Post::factory()->count(1000)->make()->toArray()
 );
 ray(microtime(true) - $start); // 0.15621304512024

- + \ No newline at end of file diff --git a/tips/reuse-the-environment-variable-value.html b/tips/reuse-the-environment-variable-value.html index 6e76af88c..97117f4ea 100644 --- a/tips/reuse-the-environment-variable-value.html +++ b/tips/reuse-the-environment-variable-value.html @@ -11,18 +11,18 @@ - + -
Skip to content

重用环境变量值

当环境变量中存在重复的变量值时,可以重用环境变量值。

可以使用此语法重用它们,而不是重写这些值。

dotenv
APP_URL=https://laravel-tips.test
+    
Skip to content

重用环境变量值

当环境变量中存在重复的变量值时,可以重用环境变量值。

可以使用此语法重用它们,而不是重写这些值。

dotenv
APP_URL=https://laravel-tips.test
 ADMIN_URL=https://laravel-tips.test
APP_URL=https://laravel-tips.test
 ADMIN_URL=https://laravel-tips.test
dotenv
APP_URL=https://laravel-tips.test
 ADMIN_URL="${APP_URL}"
APP_URL=https://laravel-tips.test
 ADMIN_URL="${APP_URL}"
- + \ No newline at end of file