From 8c5c479f26d711e240290107dff89b00fb754b77 Mon Sep 17 00:00:00 2001 From: curder Date: Fri, 2 Feb 2024 08:50:32 +0000 Subject: [PATCH] deploy: 4509ac7944cdc9ea495131d906a984ac2b5d8b92 --- 404.html | 2 +- README.html | 6 +- ...E.md.jFA-2Pyx.js => README.md.apB3GTSz.js} | 4 +- assets/README.md.apB3GTSz.lean.js | 1 + assets/README.md.jFA-2Pyx.lean.js | 1 - ...dG0Q.js => collections_all.md.oJwh_lKh.js} | 2 +- ...js => collections_all.md.oJwh_lKh.lean.js} | 0 ...t_GK.js => collections_avg.md.xLdaFj0z.js} | 2 +- ...js => collections_avg.md.xLdaFj0z.lean.js} | 0 ...bv.js => collections_chunk.md.cOnAXM54.js} | 4 +- ... => collections_chunk.md.cOnAXM54.lean.js} | 2 +- ...js => collections_collapse.md.oxuG8yyE.js} | 2 +- ... collections_collapse.md.oxuG8yyE.lean.js} | 0 ...js => collections_contains.md.iYcKzst-.js} | 2 +- ... collections_contains.md.iYcKzst-.lean.js} | 0 ....js => collections_countBy.md.l-Ea66bq.js} | 4 +- ...> collections_countBy.md.l-Ea66bq.lean.js} | 2 +- ...format-github-events-score.md.hyfCyv4u.js} | 4 +- ...t-github-events-score.md.hyfCyv4u.lean.js} | 0 ...xamples_order-info-summary.md.XqY9j1FS.js} | 2 +- ...es_order-info-summary.md.XqY9j1FS.lean.js} | 0 ...reduce-create-lookup-array.md.dvs71PEo.js} | 2 +- ...e-create-lookup-array.md.dvs71PEo.lean.js} | 0 ...6t.js => collections_first.md.S0hVTg0e.js} | 2 +- ... => collections_first.md.S0hVTg0e.lean.js} | 0 ... => collections_firstWhere.md.xLPb4fOu.js} | 2 +- ...ollections_firstWhere.md.xLPb4fOu.lean.js} | 0 ...lnQv.js => collections_get.md.8QQmXJQ1.js} | 4 +- ...js => collections_get.md.8QQmXJQ1.lean.js} | 2 +- ...jgMPke.js => others_macros.md.gakYAePd.js} | 2 +- ...n.js => others_macros.md.gakYAePd.lean.js} | 0 ...te-better-and-clearer-code.md.csYPuapg.js} | 2 +- ...tter-and-clearer-code.md.csYPuapg.lean.js} | 0 ...Z0lg.js => packages_README.md.XJEffmIi.js} | 2 +- ...js => packages_README.md.XJEffmIi.lean.js} | 2 +- assets/packages_backup.md.tXZnViYm.js | 100 ++++++++++++++ assets/packages_backup.md.tXZnViYm.lean.js | 1 + ...ackages_laravel-login-link.md.Olxf7G32.js} | 2 +- ...es_laravel-login-link.md.Olxf7G32.lean.js} | 0 ....js => partials_migrations.md.E0t3c2Hd.js} | 6 +- ...> partials_migrations.md.E0t3c2Hd.lean.js} | 0 ...Sq_p3.js => partials_model.md.dpslP7zF.js} | 10 +- ....js => partials_model.md.dpslP7zF.lean.js} | 0 ...ff9.js => partials_testing.md.fbu4V60w.js} | 36 ++--- ...s => partials_testing.md.fbu4V60w.lean.js} | 0 ....js => partials_validation.md.TinoEwuN.js} | 4 +- ...> partials_validation.md.TinoEwuN.lean.js} | 2 +- ...Ea_JL.js => partials_views.md.Xvm8Qxt4.js} | 18 +-- ....js => partials_views.md.Xvm8Qxt4.lean.js} | 0 ...ips_db-models-and-eloquent.md.ZlfaD_0T.js} | 18 +-- ...b-models-and-eloquent.md.ZlfaD_0T.lean.js} | 0 ...tory-database-batch-insert.md.f82qCgz_.js} | 2 +- ...database-batch-insert.md.f82qCgz_.lean.js} | 0 ...environment-variable-value.md.9X_QhAK_.js} | 4 +- ...onment-variable-value.md.9X_QhAK_.lean.js} | 2 +- collections/all.html | 6 +- collections/avg.html | 6 +- collections/chunk.html | 6 +- collections/chunkWhile.html | 2 +- collections/collapse.html | 6 +- collections/collect.html | 2 +- collections/combine.html | 2 +- collections/concat.html | 2 +- collections/contains.html | 6 +- collections/containsOneItem.html | 2 +- collections/containsStrict.html | 2 +- collections/count.html | 2 +- collections/countBy.html | 6 +- collections/crossJoin.html | 2 +- collections/dd.html | 2 +- collections/diff.html | 2 +- collections/diffAssoc.html | 2 +- collections/diffAssocUsing.html | 2 +- collections/diffKeys.html | 2 +- collections/diffKeysUsing.html | 2 +- collections/diffUsing.html | 2 +- collections/doesntContain.html | 2 +- collections/dump.html | 2 +- collections/duplicates.html | 2 +- collections/duplicatesStrict.html | 2 +- collections/each.html | 2 +- collections/eachSpread.html | 2 +- collections/every.html | 2 +- collections/examples/README.html | 2 +- ...-calculate-the-data-of-the-two-arrays.html | 2 +- .../examples/format-github-events-score.html | 8 +- .../get-the-corresponding-key-by-value.html | 2 +- collections/examples/map-format.html | 2 +- collections/examples/markdown-format.html | 2 +- collections/examples/order-info-summary.html | 6 +- .../using-reduce-create-lookup-array.html | 6 +- collections/examples/using-sum-method.html | 2 +- collections/except.html | 2 +- collections/filter.html | 2 +- collections/first.html | 6 +- collections/firstOrFail.html | 2 +- collections/firstWhere.html | 6 +- collections/flatMap.html | 2 +- collections/flatten.html | 2 +- collections/flip.html | 2 +- collections/forPage.html | 2 +- collections/forget.html | 2 +- collections/get.html | 6 +- collections/groupBy.html | 2 +- collections/has.html | 2 +- collections/hasAny.html | 2 +- collections/implode.html | 2 +- collections/index.html | 2 +- collections/intersect.html | 2 +- collections/intersectByKeys.html | 2 +- collections/isEmpty.html | 2 +- collections/isNotEmpty.html | 2 +- collections/join.html | 2 +- collections/keyBy.html | 2 +- collections/keys.html | 2 +- collections/last.html | 2 +- collections/lazy.html | 2 +- collections/macro.html | 2 +- collections/make.html | 2 +- collections/map.html | 2 +- collections/mapInto.html | 2 +- collections/mapSpread.html | 2 +- collections/mapToDictionary.html | 2 +- collections/mapToGroups.html | 2 +- collections/mapWithKeys.html | 2 +- collections/max.html | 2 +- collections/median.html | 2 +- collections/merge.html | 2 +- collections/mergeRecursive.html | 2 +- collections/min.html | 2 +- collections/mode.html | 2 +- collections/nth.html | 2 +- collections/only.html | 2 +- collections/pad.html | 2 +- collections/partition.html | 2 +- collections/pipe.html | 2 +- collections/pipeInto.html | 2 +- collections/pipeThrough.html | 2 +- collections/pluck.html | 2 +- collections/pop.html | 2 +- collections/prepend.html | 2 +- collections/pull.html | 2 +- collections/push.html | 2 +- collections/put.html | 2 +- collections/random.html | 2 +- collections/reduce.html | 2 +- collections/reduceSpread.html | 2 +- collections/reject.html | 2 +- collections/replace.html | 2 +- collections/replaceRecursive.html | 2 +- collections/reverse.html | 2 +- collections/search.html | 2 +- collections/shift.html | 2 +- collections/shuffle.html | 2 +- collections/skip.html | 2 +- collections/skipUntil.html | 2 +- collections/skipWhile.html | 2 +- collections/slice.html | 2 +- collections/sliding.html | 2 +- collections/sole.html | 2 +- collections/sort.html | 2 +- collections/sortBy.html | 2 +- collections/sortByDesc.html | 2 +- collections/sortDesc.html | 2 +- collections/sortKeys.html | 2 +- collections/sortKeysDesc.html | 2 +- collections/sortKeysUsing.html | 2 +- collections/splice.html | 2 +- collections/split.html | 2 +- collections/splitIn.html | 2 +- collections/sum.html | 2 +- collections/take.html | 2 +- collections/takeUntil.html | 2 +- collections/takeWhile.html | 2 +- collections/tap.html | 2 +- collections/times.html | 2 +- collections/toArray.html | 2 +- collections/toJson.html | 2 +- collections/transform.html | 2 +- collections/undot.html | 2 +- collections/union.html | 2 +- collections/unique.html | 2 +- collections/uniqueStrict.html | 2 +- collections/unless.html | 2 +- collections/unwrap.html | 2 +- collections/value.html | 2 +- collections/values.html | 2 +- collections/when.html | 2 +- collections/whenEmpty.html | 2 +- collections/whenNotEmpty.html | 2 +- collections/where.html | 2 +- collections/whereBetween.html | 2 +- collections/whereIn.html | 2 +- collections/whereInStrict.html | 2 +- collections/whereInstanceOf.html | 2 +- collections/whereNotBetween.html | 2 +- collections/whereNotIn.html | 2 +- collections/whereNotInStrict.html | 2 +- collections/whereNotNull.html | 2 +- collections/whereNull.html | 2 +- collections/whereStrict.html | 2 +- collections/wrap.html | 2 +- collections/zip.html | 2 +- hashmap.json | 2 +- index.html | 2 +- model/index.html | 2 +- model/laravel-model-caching.html | 2 +- model/laravel-model-events.html | 2 +- model/laravel-model-observers.html | 2 +- model/relationships/01-has-one.html | 2 +- model/relationships/02-has-many.html | 2 +- model/relationships/03-has-one-of-many.html | 2 +- model/relationships/04-has-one-through.html | 2 +- model/relationships/05-has-many-through.html | 2 +- model/relationships/06-belongs-to-many.html | 2 +- model/relationships/07-morph-one.html | 2 +- model/relationships/08-morph-many.html | 2 +- model/relationships/09-one-of-many.html | 2 +- model/relationships/10-morph-to-many.html | 2 +- model/relationships/README.html | 2 +- ...me-tips-for-optimize-database-queries.html | 2 +- others/README.html | 2 +- ...-command-to-generate-views-in-laravel.html | 2 +- others/helpers/numbers.html | 2 +- others/helpers/sleep.html | 2 +- ...aravel-create-custom-facade-test-demo.html | 2 +- .../laravel-import-custom-function-file.html | 2 +- others/macros.html | 6 +- ...ation-error-in-laravel-using-alpinejs.html | 2 +- .../unit-test-laravel-api-pest-framework.html | 2 +- ...ions-to-write-better-and-clearer-code.html | 6 +- packages/README.html | 6 +- packages/backup.html | 124 ++++++++++++++++++ packages/index.html | 4 +- packages/laravel-login-link.html | 6 +- packages/missing-livewire-assertions.html | 6 +- packages/pail.html | 4 +- packages/pint.html | 4 +- packages/sushi.html | 4 +- partials/README.html | 2 +- partials/migrations.html | 10 +- partials/model-relations.html | 2 +- partials/model.html | 14 +- partials/routing.html | 2 +- partials/testing.html | 40 +++--- partials/urls.html | 2 +- partials/validation.html | 6 +- partials/views.html | 22 ++-- tips/README.html | 2 +- tips/db-models-and-eloquent.html | 22 ++-- ...ptimize-factory-database-batch-insert.html | 6 +- ...files-with-laravel-using-simple-excel.html | 2 +- .../reuse-the-environment-variable-value.html | 6 +- 253 files changed, 598 insertions(+), 373 deletions(-) rename assets/{README.md.jFA-2Pyx.js => README.md.apB3GTSz.js} (83%) create mode 100644 assets/README.md.apB3GTSz.lean.js delete mode 100644 assets/README.md.jFA-2Pyx.lean.js rename assets/{collections_all.md.X8pPdG0Q.js => collections_all.md.oJwh_lKh.js} (98%) rename assets/{collections_all.md.X8pPdG0Q.lean.js => collections_all.md.oJwh_lKh.lean.js} (100%) rename assets/{collections_avg.md.-eWpt_GK.js => collections_avg.md.xLdaFj0z.js} (97%) rename assets/{collections_avg.md.-eWpt_GK.lean.js => collections_avg.md.xLdaFj0z.lean.js} (100%) rename assets/{collections_chunk.md.aauTVJbv.js => collections_chunk.md.cOnAXM54.js} (96%) rename assets/{collections_chunk.md.aauTVJbv.lean.js => collections_chunk.md.cOnAXM54.lean.js} (69%) rename assets/{collections_collapse.md.leJkU4Xb.js => collections_collapse.md.oxuG8yyE.js} (97%) rename assets/{collections_collapse.md.leJkU4Xb.lean.js => collections_collapse.md.oxuG8yyE.lean.js} (100%) rename assets/{collections_contains.md._c9S_erV.js => collections_contains.md.iYcKzst-.js} (96%) rename assets/{collections_contains.md._c9S_erV.lean.js => collections_contains.md.iYcKzst-.lean.js} (100%) rename assets/{collections_countBy.md.O1bayoZp.js => collections_countBy.md.l-Ea66bq.js} (94%) rename assets/{collections_countBy.md.O1bayoZp.lean.js => collections_countBy.md.l-Ea66bq.lean.js} (85%) rename assets/{collections_examples_format-github-events-score.md.wfxYnsHX.js => collections_examples_format-github-events-score.md.hyfCyv4u.js} (98%) rename assets/{collections_examples_format-github-events-score.md.wfxYnsHX.lean.js => collections_examples_format-github-events-score.md.hyfCyv4u.lean.js} (100%) rename assets/{collections_examples_order-info-summary.md.bN_UE0uA.js => collections_examples_order-info-summary.md.XqY9j1FS.js} (98%) rename assets/{collections_examples_order-info-summary.md.bN_UE0uA.lean.js => collections_examples_order-info-summary.md.XqY9j1FS.lean.js} (100%) rename assets/{collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.js => collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.js} (96%) rename assets/{collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.lean.js => collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.lean.js} (100%) rename assets/{collections_first.md.zfZ7b16t.js => collections_first.md.S0hVTg0e.js} (95%) rename assets/{collections_first.md.zfZ7b16t.lean.js => collections_first.md.S0hVTg0e.lean.js} (100%) rename assets/{collections_firstWhere.md.KoMr1nHq.js => collections_firstWhere.md.xLPb4fOu.js} (97%) rename assets/{collections_firstWhere.md.KoMr1nHq.lean.js => collections_firstWhere.md.xLPb4fOu.lean.js} (100%) rename assets/{collections_get.md.8UpplnQv.js => collections_get.md.8QQmXJQ1.js} (93%) rename assets/{collections_get.md.8UpplnQv.lean.js => collections_get.md.8QQmXJQ1.lean.js} (69%) rename assets/{others_macros.md.x0jgMPke.js => others_macros.md.gakYAePd.js} (99%) rename assets/{others_macros.md.x0jgMPke.lean.js => others_macros.md.gakYAePd.lean.js} (100%) rename assets/{others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.js => others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.js} (98%) rename assets/{others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.lean.js => others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.lean.js} (100%) rename assets/{packages_README.md.MxtBZ0lg.js => packages_README.md.XJEffmIi.js} (66%) rename assets/{packages_README.md.MxtBZ0lg.lean.js => packages_README.md.XJEffmIi.lean.js} (55%) create mode 100644 assets/packages_backup.md.tXZnViYm.js create mode 100644 assets/packages_backup.md.tXZnViYm.lean.js rename assets/{packages_laravel-login-link.md.JvVMGzDJ.js => packages_laravel-login-link.md.Olxf7G32.js} (99%) rename assets/{packages_laravel-login-link.md.JvVMGzDJ.lean.js => packages_laravel-login-link.md.Olxf7G32.lean.js} (100%) rename assets/{partials_migrations.md.Tz41kgD7.js => partials_migrations.md.E0t3c2Hd.js} (98%) rename assets/{partials_migrations.md.Tz41kgD7.lean.js => partials_migrations.md.E0t3c2Hd.lean.js} (100%) rename assets/{partials_model.md.vO6Sq_p3.js => partials_model.md.dpslP7zF.js} (99%) rename assets/{partials_model.md.vO6Sq_p3.lean.js => partials_model.md.dpslP7zF.lean.js} (100%) rename assets/{partials_testing.md.e6oc5ff9.js => partials_testing.md.fbu4V60w.js} (98%) rename assets/{partials_testing.md.e6oc5ff9.lean.js => partials_testing.md.fbu4V60w.lean.js} (100%) rename assets/{partials_validation.md.xS4DbwrE.js => partials_validation.md.TinoEwuN.js} (99%) rename assets/{partials_validation.md.xS4DbwrE.lean.js => partials_validation.md.TinoEwuN.lean.js} (85%) rename assets/{partials_views.md.cI6Ea_JL.js => partials_views.md.Xvm8Qxt4.js} (97%) rename assets/{partials_views.md.cI6Ea_JL.lean.js => partials_views.md.Xvm8Qxt4.lean.js} (100%) rename assets/{tips_db-models-and-eloquent.md.QeyCv8Q5.js => tips_db-models-and-eloquent.md.ZlfaD_0T.js} (99%) rename assets/{tips_db-models-and-eloquent.md.QeyCv8Q5.lean.js => tips_db-models-and-eloquent.md.ZlfaD_0T.lean.js} (100%) rename assets/{tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.js => tips_optimize-factory-database-batch-insert.md.f82qCgz_.js} (98%) rename assets/{tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.lean.js => tips_optimize-factory-database-batch-insert.md.f82qCgz_.lean.js} (100%) rename assets/{tips_reuse-the-environment-variable-value.md.aGGykNAC.js => tips_reuse-the-environment-variable-value.md.9X_QhAK_.js} (76%) rename assets/{tips_reuse-the-environment-variable-value.md.aGGykNAC.lean.js => tips_reuse-the-environment-variable-value.md.9X_QhAK_.lean.js} (62%) create mode 100644 packages/backup.html diff --git a/404.html b/404.html index b3eca06ec..61e9b70d8 100644 --- a/404.html +++ b/404.html @@ -16,7 +16,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 108e0c213..a267cee35 100644 --- a/README.html +++ b/README.html @@ -12,13 +12,13 @@ - + -
Skip to content

Laravel 学习记录

开发

bash
# install in your project
+    
Skip to content

Laravel 学习记录

开发

bash
# install in your project
 yarn
 
 # start writing
@@ -33,7 +33,7 @@
 
 # build to static files
 npx prod
- + \ No newline at end of file diff --git a/assets/README.md.jFA-2Pyx.js b/assets/README.md.apB3GTSz.js similarity index 83% rename from assets/README.md.jFA-2Pyx.js rename to assets/README.md.apB3GTSz.js index 2009c29b5..99a8d1ce7 100644 --- a/assets/README.md.jFA-2Pyx.js +++ b/assets/README.md.apB3GTSz.js @@ -1,4 +1,4 @@ -import{_ as s,c as a,o as i,V as n}from"./chunks/framework.HIcQKaVu.js";const b=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),t={name:"README.md"},l=n(`

Laravel 学习记录

开发

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

Laravel 学习记录

开发

bash
# install in your project
 yarn
 
 # start writing
@@ -12,4 +12,4 @@ import{_ as s,c as a,o as i,V as n}from"./chunks/framework.HIcQKaVu.js";const b=
 npx watch
 
 # build to static files
-npx prod
`,3),e=[l];function p(h,r,d,c,k,o){return i(),a("div",null,e)}const _=s(t,[["render",p]]);export{b as __pageData,_ as default}; +npx prod
`,3),e=[t];function p(h,r,d,c,k,o){return i(),a("div",null,e)}const y=s(l,[["render",p]]);export{b as __pageData,y as default}; diff --git a/assets/README.md.apB3GTSz.lean.js b/assets/README.md.apB3GTSz.lean.js new file mode 100644 index 000000000..e7e18d1ed --- /dev/null +++ b/assets/README.md.apB3GTSz.lean.js @@ -0,0 +1 @@ +import{_ as s,c as a,o as i,V as n}from"./chunks/framework.HIcQKaVu.js";const b=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),l={name:"README.md"},t=n("",3),e=[t];function p(h,r,d,c,k,o){return i(),a("div",null,e)}const y=s(l,[["render",p]]);export{b as __pageData,y as default}; diff --git a/assets/README.md.jFA-2Pyx.lean.js b/assets/README.md.jFA-2Pyx.lean.js deleted file mode 100644 index d703e1b3b..000000000 --- a/assets/README.md.jFA-2Pyx.lean.js +++ /dev/null @@ -1 +0,0 @@ -import{_ as s,c as a,o as i,V as n}from"./chunks/framework.HIcQKaVu.js";const b=JSON.parse('{"title":"Laravel 学习记录","description":"","frontmatter":{},"headers":[],"relativePath":"README.md","filePath":"README.md","lastUpdated":1677228715000}'),t={name:"README.md"},l=n("",3),e=[l];function p(h,r,d,c,k,o){return i(),a("div",null,e)}const _=s(t,[["render",p]]);export{b as __pageData,_ as default}; diff --git a/assets/collections_all.md.X8pPdG0Q.js b/assets/collections_all.md.oJwh_lKh.js similarity index 98% rename from assets/collections_all.md.X8pPdG0Q.js rename to assets/collections_all.md.oJwh_lKh.js index 919722b7e..02665d504 100644 --- a/assets/collections_all.md.X8pPdG0Q.js +++ b/assets/collections_all.md.oJwh_lKh.js @@ -1,7 +1,7 @@ import{_ as s,c as i,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"all","description":"","frontmatter":{},"headers":[],"relativePath":"collections/all.md","filePath":"collections/all.md","lastUpdated":1695352325000}'),t={name:"collections/all.md"},h=l(`

all

该方法返回该集合表示的底层数组

php
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();
 
 /**
diff --git a/assets/collections_all.md.X8pPdG0Q.lean.js b/assets/collections_all.md.oJwh_lKh.lean.js
similarity index 100%
rename from assets/collections_all.md.X8pPdG0Q.lean.js
rename to assets/collections_all.md.oJwh_lKh.lean.js
diff --git a/assets/collections_avg.md.-eWpt_GK.js b/assets/collections_avg.md.xLdaFj0z.js
similarity index 97%
rename from assets/collections_avg.md.-eWpt_GK.js
rename to assets/collections_avg.md.xLdaFj0z.js
index 91d0286d3..b9f92571f 100644
--- a/assets/collections_avg.md.-eWpt_GK.js
+++ b/assets/collections_avg.md.xLdaFj0z.js
@@ -1,4 +1,4 @@
-import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=JSON.parse('{"title":"avg","description":"","frontmatter":{},"headers":[],"relativePath":"collections/avg.md","filePath":"collections/avg.md","lastUpdated":1695352397000}'),k={name:"collections/avg.md"},n=h(`

avg

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

一些示例

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

avg

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

一些示例

php
// 获取一维数组
 collect([10, 20, 30])->average(); // 20
 
 // 获取二维数组的平均值
diff --git a/assets/collections_avg.md.-eWpt_GK.lean.js b/assets/collections_avg.md.xLdaFj0z.lean.js
similarity index 100%
rename from assets/collections_avg.md.-eWpt_GK.lean.js
rename to assets/collections_avg.md.xLdaFj0z.lean.js
diff --git a/assets/collections_chunk.md.aauTVJbv.js b/assets/collections_chunk.md.cOnAXM54.js
similarity index 96%
rename from assets/collections_chunk.md.aauTVJbv.js
rename to assets/collections_chunk.md.cOnAXM54.js
index 9b8448497..e434e5e14 100644
--- a/assets/collections_chunk.md.aauTVJbv.js
+++ b/assets/collections_chunk.md.cOnAXM54.js
@@ -1,4 +1,4 @@
-import{_ as i,c as s,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),t={name:"collections/chunk.md"},n=l(`

chuck

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

一些示例

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

chuck

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

一些示例

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

相关方法

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

相关方法

`,6),h=[n];function k(p,e,c,d,r,o){return a(),s("div",null,h)}const E=i(t,[["render",k]]);export{g as __pageData,E as default}; diff --git a/assets/collections_chunk.md.aauTVJbv.lean.js b/assets/collections_chunk.md.cOnAXM54.lean.js similarity index 69% rename from assets/collections_chunk.md.aauTVJbv.lean.js rename to assets/collections_chunk.md.cOnAXM54.lean.js index e76aa0ae1..82620de47 100644 --- a/assets/collections_chunk.md.aauTVJbv.lean.js +++ b/assets/collections_chunk.md.cOnAXM54.lean.js @@ -1 +1 @@ -import{_ as i,c as s,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),t={name:"collections/chunk.md"},n=l("",6),h=[n];function k(e,p,c,d,r,o){return a(),s("div",null,h)}const E=i(t,[["render",k]]);export{g as __pageData,E as default}; +import{_ as i,c as s,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"chuck","description":"","frontmatter":{},"headers":[],"relativePath":"collections/chunk.md","filePath":"collections/chunk.md","lastUpdated":1697179951000}'),t={name:"collections/chunk.md"},n=l("",6),h=[n];function k(p,e,c,d,r,o){return a(),s("div",null,h)}const E=i(t,[["render",k]]);export{g as __pageData,E as default}; diff --git a/assets/collections_collapse.md.leJkU4Xb.js b/assets/collections_collapse.md.oxuG8yyE.js similarity index 97% rename from assets/collections_collapse.md.leJkU4Xb.js rename to assets/collections_collapse.md.oxuG8yyE.js index 5ecf94b25..a6353f68f 100644 --- a/assets/collections_collapse.md.leJkU4Xb.js +++ b/assets/collections_collapse.md.oxuG8yyE.js @@ -1,4 +1,4 @@ -import{_ as s,c as i,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"collapse","description":"","frontmatter":{},"headers":[],"relativePath":"collections/collapse.md","filePath":"collections/collapse.md","lastUpdated":1695352109000}'),t={name:"collections/collapse.md"},h=l(`

collapse

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

相关示例

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

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.leJkU4Xb.lean.js b/assets/collections_collapse.md.oxuG8yyE.lean.js
similarity index 100%
rename from assets/collections_collapse.md.leJkU4Xb.lean.js
rename to assets/collections_collapse.md.oxuG8yyE.lean.js
diff --git a/assets/collections_contains.md._c9S_erV.js b/assets/collections_contains.md.iYcKzst-.js
similarity index 96%
rename from assets/collections_contains.md._c9S_erV.js
rename to assets/collections_contains.md.iYcKzst-.js
index 63f29fb5f..5be8dac20 100644
--- a/assets/collections_contains.md._c9S_erV.js
+++ b/assets/collections_contains.md.iYcKzst-.js
@@ -1,4 +1,4 @@
-import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const o=JSON.parse('{"title":"contains","description":"","frontmatter":{},"headers":[],"relativePath":"collections/contains.md","filePath":"collections/contains.md","lastUpdated":1696669800000}'),t={name:"collections/contains.md"},n=h(`

contains

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

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

contains

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

php
collect(['value'])->contains('value1'); // false
 collect(['value'])->contains('value'); // true
 collect(['key' => 'value'])->contains('value'); // true
php
$collection = collect([
   ['product' => 'Desk', 'price' => 200],
diff --git a/assets/collections_contains.md._c9S_erV.lean.js b/assets/collections_contains.md.iYcKzst-.lean.js
similarity index 100%
rename from assets/collections_contains.md._c9S_erV.lean.js
rename to assets/collections_contains.md.iYcKzst-.lean.js
diff --git a/assets/collections_countBy.md.O1bayoZp.js b/assets/collections_countBy.md.l-Ea66bq.js
similarity index 94%
rename from assets/collections_countBy.md.O1bayoZp.js
rename to assets/collections_countBy.md.l-Ea66bq.js
index 24ed430a8..6942b16bb 100644
--- a/assets/collections_countBy.md.O1bayoZp.js
+++ b/assets/collections_countBy.md.l-Ea66bq.js
@@ -1,5 +1,5 @@
-import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"countBy","description":"","frontmatter":{},"headers":[],"relativePath":"collections/countBy.md","filePath":"collections/countBy.md","lastUpdated":1695368331000}'),h={name:"collections/countBy.md"},l=t(`

countBy

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

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

countBy

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

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

相关方法

`,5),n=[l];function e(k,p,o,d,r,c){return a(),i("div",null,n)}const y=s(h,[["render",e]]);export{g as __pageData,y as default}; +); // ['gmail.com' => 2, 'yahoo.com' => 1]

相关方法

`,5),n=[l];function e(p,k,o,d,r,c){return a(),i("div",null,n)}const y=s(h,[["render",e]]);export{g as __pageData,y as default}; diff --git a/assets/collections_countBy.md.O1bayoZp.lean.js b/assets/collections_countBy.md.l-Ea66bq.lean.js similarity index 85% rename from assets/collections_countBy.md.O1bayoZp.lean.js rename to assets/collections_countBy.md.l-Ea66bq.lean.js index 91d566979..cc962dcc1 100644 --- a/assets/collections_countBy.md.O1bayoZp.lean.js +++ b/assets/collections_countBy.md.l-Ea66bq.lean.js @@ -1 +1 @@ -import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"countBy","description":"","frontmatter":{},"headers":[],"relativePath":"collections/countBy.md","filePath":"collections/countBy.md","lastUpdated":1695368331000}'),h={name:"collections/countBy.md"},l=t("",5),n=[l];function e(k,p,o,d,r,c){return a(),i("div",null,n)}const y=s(h,[["render",e]]);export{g as __pageData,y as default}; +import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const g=JSON.parse('{"title":"countBy","description":"","frontmatter":{},"headers":[],"relativePath":"collections/countBy.md","filePath":"collections/countBy.md","lastUpdated":1695368331000}'),h={name:"collections/countBy.md"},l=t("",5),n=[l];function e(p,k,o,d,r,c){return a(),i("div",null,n)}const y=s(h,[["render",e]]);export{g as __pageData,y as default}; diff --git a/assets/collections_examples_format-github-events-score.md.wfxYnsHX.js b/assets/collections_examples_format-github-events-score.md.hyfCyv4u.js similarity index 98% rename from assets/collections_examples_format-github-events-score.md.wfxYnsHX.js rename to assets/collections_examples_format-github-events-score.md.hyfCyv4u.js index 1436fb53e..aa7638d7c 100644 --- a/assets/collections_examples_format-github-events-score.md.wfxYnsHX.js +++ b/assets/collections_examples_format-github-events-score.md.hyfCyv4u.js @@ -24,7 +24,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F= } } -dd($score); // 输出 134

使用 pluckmapsum 方法

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

使用 pluckmapsum 方法

php
$events = collect(
   Http::get('https://api.github.com/users/curder/events')->json()
 );
 
@@ -76,7 +76,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
       '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.wfxYnsHX.lean.js b/assets/collections_examples_format-github-events-score.md.hyfCyv4u.lean.js
similarity index 100%
rename from assets/collections_examples_format-github-events-score.md.wfxYnsHX.lean.js
rename to assets/collections_examples_format-github-events-score.md.hyfCyv4u.lean.js
diff --git a/assets/collections_examples_order-info-summary.md.bN_UE0uA.js b/assets/collections_examples_order-info-summary.md.XqY9j1FS.js
similarity index 98%
rename from assets/collections_examples_order-info-summary.md.bN_UE0uA.js
rename to assets/collections_examples_order-info-summary.md.XqY9j1FS.js
index 6fdeac54a..50c318988 100644
--- a/assets/collections_examples_order-info-summary.md.bN_UE0uA.js
+++ b/assets/collections_examples_order-info-summary.md.XqY9j1FS.js
@@ -55,7 +55,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const y=
         'qty' => 3,
         'customer_name'=>'Mandy',
     ],
-];
php
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
+];
php
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
 );
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->sum(
diff --git a/assets/collections_examples_order-info-summary.md.bN_UE0uA.lean.js b/assets/collections_examples_order-info-summary.md.XqY9j1FS.lean.js
similarity index 100%
rename from assets/collections_examples_order-info-summary.md.bN_UE0uA.lean.js
rename to assets/collections_examples_order-info-summary.md.XqY9j1FS.lean.js
diff --git a/assets/collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.js b/assets/collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.js
similarity index 96%
rename from assets/collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.js
rename to assets/collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.js
index 5c5ad48b5..ee3ce63f5 100644
--- a/assets/collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.js
+++ b/assets/collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.js
@@ -18,7 +18,7 @@ import{_ as s,c as i,o as a,V as l}from"./chunks/framework.HIcQKaVu.js";const c=
   '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"]
php
$emails = [];
 foreach ($employees as $key => $value) {
diff --git a/assets/collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.lean.js b/assets/collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.lean.js
similarity index 100%
rename from assets/collections_examples_using-reduce-create-lookup-array.md.wR_t-2yG.lean.js
rename to assets/collections_examples_using-reduce-create-lookup-array.md.dvs71PEo.lean.js
diff --git a/assets/collections_first.md.zfZ7b16t.js b/assets/collections_first.md.S0hVTg0e.js
similarity index 95%
rename from assets/collections_first.md.zfZ7b16t.js
rename to assets/collections_first.md.S0hVTg0e.js
index 7db834bb5..706159e04 100644
--- a/assets/collections_first.md.zfZ7b16t.js
+++ b/assets/collections_first.md.S0hVTg0e.js
@@ -1,4 +1,4 @@
-import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const c=JSON.parse('{"title":"first","description":"","frontmatter":{},"headers":[],"relativePath":"collections/first.md","filePath":"collections/first.md","lastUpdated":1695377514000}'),h={name:"collections/first.md"},l=t(`

first

返回集合中第一个元素

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

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
 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

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

其它方法

`,6),k=[l];function p(n,e,r,d,E,g){return a(),i("div",null,k)}const y=s(h,[["render",p]]);export{c as __pageData,y as default}; diff --git a/assets/collections_first.md.zfZ7b16t.lean.js b/assets/collections_first.md.S0hVTg0e.lean.js similarity index 100% rename from assets/collections_first.md.zfZ7b16t.lean.js rename to assets/collections_first.md.S0hVTg0e.lean.js diff --git a/assets/collections_firstWhere.md.KoMr1nHq.js b/assets/collections_firstWhere.md.xLPb4fOu.js similarity index 97% rename from assets/collections_firstWhere.md.KoMr1nHq.js rename to assets/collections_firstWhere.md.xLPb4fOu.js index 222eccc47..3a5595054 100644 --- a/assets/collections_firstWhere.md.KoMr1nHq.js +++ b/assets/collections_firstWhere.md.xLPb4fOu.js @@ -1,4 +1,4 @@ -import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=JSON.parse('{"title":"firstWhere","description":"","frontmatter":{},"headers":[],"relativePath":"collections/firstWhere.md","filePath":"collections/firstWhere.md","lastUpdated":1695378156000}'),t={name:"collections/firstWhere.md"},k=h(`

firstWhere

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

php
collect([
+import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=JSON.parse('{"title":"firstWhere","description":"","frontmatter":{},"headers":[],"relativePath":"collections/firstWhere.md","filePath":"collections/firstWhere.md","lastUpdated":1695378156000}'),t={name:"collections/firstWhere.md"},k=h(`

firstWhere

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

php
collect([
   ['product' => 'apples', 'price' => 50],
   ['product' => 'pears', 'price' => 50],
   ['product' => 'banners', 'price' => 50],
diff --git a/assets/collections_firstWhere.md.KoMr1nHq.lean.js b/assets/collections_firstWhere.md.xLPb4fOu.lean.js
similarity index 100%
rename from assets/collections_firstWhere.md.KoMr1nHq.lean.js
rename to assets/collections_firstWhere.md.xLPb4fOu.lean.js
diff --git a/assets/collections_get.md.8UpplnQv.js b/assets/collections_get.md.8QQmXJQ1.js
similarity index 93%
rename from assets/collections_get.md.8UpplnQv.js
rename to assets/collections_get.md.8QQmXJQ1.js
index 85c4b1cc3..0c6fa6a96 100644
--- a/assets/collections_get.md.8UpplnQv.js
+++ b/assets/collections_get.md.8QQmXJQ1.js
@@ -1,4 +1,4 @@
-import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const c=JSON.parse('{"title":"get","description":"","frontmatter":{},"headers":[],"relativePath":"collections/get.md","filePath":"collections/get.md","lastUpdated":1695380014000}'),l={name:"collections/get.md"},h=t(`

get

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

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

get

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

php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('name'); // "taylor"
php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('foo', 'bar'); // bar
php
// 如果指定的键不存在,会调用回调
 collect(['name' => 'taylor', 'framework' => 'laravel'])
@@ -8,4 +8,4 @@ import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const c=
             // some logic
             return 'bar';
         }
-    ); // bar

相关方法

`,5),n=[h];function e(p,k,r,d,g,E){return a(),i("div",null,n)}const F=s(l,[["render",e]]);export{c as __pageData,F as default}; + ); // bar

相关方法

`,5),n=[h];function p(e,k,r,d,g,E){return a(),i("div",null,n)}const F=s(l,[["render",p]]);export{c as __pageData,F as default}; diff --git a/assets/collections_get.md.8UpplnQv.lean.js b/assets/collections_get.md.8QQmXJQ1.lean.js similarity index 69% rename from assets/collections_get.md.8UpplnQv.lean.js rename to assets/collections_get.md.8QQmXJQ1.lean.js index 5b82b37ae..b317eb263 100644 --- a/assets/collections_get.md.8UpplnQv.lean.js +++ b/assets/collections_get.md.8QQmXJQ1.lean.js @@ -1 +1 @@ -import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const c=JSON.parse('{"title":"get","description":"","frontmatter":{},"headers":[],"relativePath":"collections/get.md","filePath":"collections/get.md","lastUpdated":1695380014000}'),l={name:"collections/get.md"},h=t("",5),n=[h];function e(p,k,r,d,g,E){return a(),i("div",null,n)}const F=s(l,[["render",e]]);export{c as __pageData,F as default}; +import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const c=JSON.parse('{"title":"get","description":"","frontmatter":{},"headers":[],"relativePath":"collections/get.md","filePath":"collections/get.md","lastUpdated":1695380014000}'),l={name:"collections/get.md"},h=t("",5),n=[h];function p(e,k,r,d,g,E){return a(),i("div",null,n)}const F=s(l,[["render",p]]);export{c as __pageData,F as default}; diff --git a/assets/others_macros.md.x0jgMPke.js b/assets/others_macros.md.gakYAePd.js similarity index 99% rename from assets/others_macros.md.x0jgMPke.js rename to assets/others_macros.md.gakYAePd.js index c5a8ea03b..dbc38cea2 100644 --- a/assets/others_macros.md.x0jgMPke.js +++ b/assets/others_macros.md.gakYAePd.js @@ -88,7 +88,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const c= { Str::mixin(new StrMixin); //[!code ++] } -}

现在,如果在 Str 类上测试 isLength()appendTo() 方法,将得到相同的结果。

一些示例

Model

php
<?php
+}

现在,如果在 Str 类上测试 isLength()appendTo() 方法,将得到相同的结果。

一些示例

Model

php
<?php
 
 use Illuminate\\Support\\ServiceProvider;
 use Illuminate\\Database\\Eloquent\\Builder;
diff --git a/assets/others_macros.md.x0jgMPke.lean.js b/assets/others_macros.md.gakYAePd.lean.js
similarity index 100%
rename from assets/others_macros.md.x0jgMPke.lean.js
rename to assets/others_macros.md.gakYAePd.lean.js
diff --git a/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.js b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.js
similarity index 98%
rename from assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.js
rename to assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.js
index 7322ba4dd..9badaf2be 100644
--- a/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.js
+++ b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.js
@@ -30,7 +30,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.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.x3YUnaaX.lean.js b/assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.lean.js
similarity index 100%
rename from assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.x3YUnaaX.lean.js
rename to assets/others_using-custom-exceptions-to-write-better-and-clearer-code.md.csYPuapg.lean.js
diff --git a/assets/packages_README.md.MxtBZ0lg.js b/assets/packages_README.md.XJEffmIi.js
similarity index 66%
rename from assets/packages_README.md.MxtBZ0lg.js
rename to assets/packages_README.md.XJEffmIi.js
index 2d33648e5..b4db20448 100644
--- a/assets/packages_README.md.MxtBZ0lg.js
+++ b/assets/packages_README.md.XJEffmIi.js
@@ -1 +1 @@
-import{_ as a,c as e,o as l,V as t}from"./chunks/framework.HIcQKaVu.js";const f=JSON.parse('{"title":"Laravel 扩展","description":"","frontmatter":{},"headers":[],"relativePath":"packages/README.md","filePath":"packages/README.md","lastUpdated":1706091305000}'),i={name:"packages/README.md"},r=t('

Laravel 扩展

',2),s=[r];function n(o,_,c,h,d,p){return l(),e("div",null,s)}const v=a(i,[["render",n]]);export{f as __pageData,v as default}; +import{_ as a,c as e,o as l,V as t}from"./chunks/framework.HIcQKaVu.js";const f=JSON.parse('{"title":"Laravel 扩展","description":"","frontmatter":{},"headers":[],"relativePath":"packages/README.md","filePath":"packages/README.md","lastUpdated":1706863779000}'),i={name:"packages/README.md"},r=t('

Laravel 扩展

',2),s=[r];function n(o,_,c,h,p,d){return l(),e("div",null,s)}const v=a(i,[["render",n]]);export{f as __pageData,v as default}; diff --git a/assets/packages_README.md.MxtBZ0lg.lean.js b/assets/packages_README.md.XJEffmIi.lean.js similarity index 55% rename from assets/packages_README.md.MxtBZ0lg.lean.js rename to assets/packages_README.md.XJEffmIi.lean.js index b3f5729a2..a406fcb69 100644 --- a/assets/packages_README.md.MxtBZ0lg.lean.js +++ b/assets/packages_README.md.XJEffmIi.lean.js @@ -1 +1 @@ -import{_ as a,c as e,o as l,V as t}from"./chunks/framework.HIcQKaVu.js";const f=JSON.parse('{"title":"Laravel 扩展","description":"","frontmatter":{},"headers":[],"relativePath":"packages/README.md","filePath":"packages/README.md","lastUpdated":1706091305000}'),i={name:"packages/README.md"},r=t("",2),s=[r];function n(o,_,c,h,d,p){return l(),e("div",null,s)}const v=a(i,[["render",n]]);export{f as __pageData,v as default}; +import{_ as a,c as e,o as l,V as t}from"./chunks/framework.HIcQKaVu.js";const f=JSON.parse('{"title":"Laravel 扩展","description":"","frontmatter":{},"headers":[],"relativePath":"packages/README.md","filePath":"packages/README.md","lastUpdated":1706863779000}'),i={name:"packages/README.md"},r=t("",2),s=[r];function n(o,_,c,h,p,d){return l(),e("div",null,s)}const v=a(i,[["render",n]]);export{f as __pageData,v as default}; diff --git a/assets/packages_backup.md.tXZnViYm.js b/assets/packages_backup.md.tXZnViYm.js new file mode 100644 index 000000000..e76974bb5 --- /dev/null +++ b/assets/packages_backup.md.tXZnViYm.js @@ -0,0 +1,100 @@ +import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=JSON.parse('{"title":"spatie/laravel-backup","description":"","frontmatter":{},"headers":[],"relativePath":"packages/backup.md","filePath":"packages/backup.md","lastUpdated":1706863779000}'),p={name:"packages/backup.md"},h=n(`

spatie/laravel-backup

Laravel Backup 允许创建应用程序的备份,包括数据库、源代码或用户上传的文件。

备份可以存储在配置的自定义文件系统上,比如 S3、七牛云或者 ftp 等。

当备份出现问题时,该扩展包还可以通过邮件等发送通知。

安装

通过 Composer 安装该软件包:

bash
composer require spatie/laravel-backup

配置

使用下面的命令发布配置文件 config/backup.php

bash
php artisan vendor:publish --provider="Spatie\\Backup\\BackupServiceProvider"

建议修改配置文件内容:

php
<?php
+
+ 'backup' => [
+        // ...
+        'name' => env('APP_NAME', 'laravel-backup'), 
+        'name' => env('BACKUP_NAME', 'laravel-backup'), 
+        'destination' => [
+            // ...
+            'disks' => [ 
+                'local', 
+            ], 
+            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
+        ],
+    ],
+    'monitor_backups' => [
+        [
+            'name' => env('APP_NAME', 'laravel-backup'), 
+            'disks' => ['local'], 
+            'name' => env('BACKUP_NAME', 'laravel-backup'), 
+            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
+            'health_checks' => [
+                \\Spatie\\Backup\\Tasks\\Monitor\\HealthChecks\\MaximumAgeInDays::class => 1,
+                \\Spatie\\Backup\\Tasks\\Monitor\\HealthChecks\\MaximumStorageInMegabytes::class => 5000,
+            ],
+        ],
+    ],

然后可以在 .env 配置文件中添加两个自定义环境变量 BACKUP_NAME 备份名称和 BACKUP_DISKS 需要备份到的磁盘。

使用

常用命令

  • 备份所有文件

    bash
    php artisan backup:run
  • 仅备份数据库

    bash
    php artisan backup:run --only-db
  • 列出所有备份文件

    bash
    php artisan backup:list
  • 清空旧备份文件

    bash
    php artisan backup:clean

通知

默认情况下,备份任务完成后会通过发送通知到 your@example.com 用户。

可以通过 config/backup.php 文件中的 config('backup.notifications.mail') 配置项来修改通知配置。

或者通过 config/backup.php 文件中的 config('backup.notifications.notifications') 配置项移除 mail 来关闭邮件通知。

备份到七牛云

默认数据的备份文件放在本地,可以配置一些其他存储方式,比如七牛云存储。

  1. 安装驱动依赖

    bash
    composer require overtrue/laravel-filesystem-qiniu
  2. 配置 config/filesystems.php 文件

    php
    <?php
    +
    +return [
    +    // ...
    +    'disks' => [
    +        // ...
    +        'qiniu-backup' => [ 
    +            'driver' => 'qiniu', 
    +            'access_key' => env('BACKUP_QINIU_ACCESS_KEY', ''), 
    +            'secret_key' => env('BACKUP_QINIU_SECRET_KEY', ''), 
    +            'bucket' => env('BACKUP_QINIU_BUCKET', ''), 
    +            'domain' => env('BACKUP_QINIU_DOMAIN', ''),  
    +        ], 
    +    ]
    +    // ...
    +];
  3. 修改 config/backup.php 文件中关于 disks 的配置

    php
    <?php
    +return [
    +    'backup' => [
    +        // ...
    +        'destination' => [
    +            // ...
    +            'disks' => [ 
    +                'local', 
    +            ], 
    +            'disks' => explode(',', env('BACKUP_DISKS', 'local')), [ 
    +        ],
    +        // ...
    +    ],
    +    'monitor_backups' => [
    +        [
    +            // ...
    +            'disks' => ['local'],
    +            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
    +            // ...
    +        ],
    +        // ...
    +   ],
    +];
  4. 本地 .env 文件新增环境变量

    dotenv
    # Backup
    +BACKUP_QINIU_ACCESS_KEY=
    +BACKUP_QINIU_SECRET_KEY=
    +BACKUP_QINIU_BUCKET=my-backup
    +BACKUP_QINIU_DOMAIN=https://backup.domain.com
    +# support local、qiniu-backup
    +BACKUP_DISKS=local,qiniu-backup

备份定时任务

php
<?php
+
+namespace App\\Console;
+
+use Illuminate\\Console\\Scheduling\\Schedule;
+use Illuminate\\Foundation\\Console\\Kernel as ConsoleKernel;
+
+class Kernel extends ConsoleKernel
+{
+    protected function schedule(Schedule $schedule): void
+    {
+        $schedule->command('backup:run --only-db')->daily()->at('02:05'); // 凌晨2点5分备份数据库
+        $schedule->command('backup:clean')->daily()->at('02:05'); // 凌晨2点5分清理旧的备份
+        $schedule->command('backup:monitor')->daily()->at('10:05'); // 早上10点05分检查数据库备份
+    }
+    // ...
+}

mysql-dump 命令路径

  1. config/database.php 中添加自定义配置
    php
    <?php
    +
    +use Illuminate\\Support\\Str;
    +
    +return [
    +    'connections' => [
    +
    +        'mysql' => [
    +            // ...
    +            'dump' => [ 
    +                'dump_binary_path' => env('DUMP_BINARY_PATH', '/usr/local/mysql/bin'), 
    +            ], 
    +        ],
    +    ],
    +];
  2. 在本地环境文件 .env 中添加
dotenv
# For Apple M1
+DUMP_BINARY_PATH=/opt/homebrew/bin
`,28),l=[h];function k(t,e,d,E,r,g){return a(),i("div",null,l)}const y=s(p,[["render",k]]);export{F as __pageData,y as default}; diff --git a/assets/packages_backup.md.tXZnViYm.lean.js b/assets/packages_backup.md.tXZnViYm.lean.js new file mode 100644 index 000000000..e2ff76940 --- /dev/null +++ b/assets/packages_backup.md.tXZnViYm.lean.js @@ -0,0 +1 @@ +import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=JSON.parse('{"title":"spatie/laravel-backup","description":"","frontmatter":{},"headers":[],"relativePath":"packages/backup.md","filePath":"packages/backup.md","lastUpdated":1706863779000}'),p={name:"packages/backup.md"},h=n("",28),l=[h];function k(t,e,d,E,r,g){return a(),i("div",null,l)}const y=s(p,[["render",k]]);export{F as __pageData,y as default}; diff --git a/assets/packages_laravel-login-link.md.JvVMGzDJ.js b/assets/packages_laravel-login-link.md.Olxf7G32.js similarity index 99% rename from assets/packages_laravel-login-link.md.JvVMGzDJ.js rename to assets/packages_laravel-login-link.md.Olxf7G32.js index c7deee2f8..cb68f4fe7 100644 --- a/assets/packages_laravel-login-link.md.JvVMGzDJ.js +++ b/assets/packages_laravel-login-link.md.Olxf7G32.js @@ -1,4 +1,4 @@ -import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=JSON.parse('{"title":"快速登录 spatie/laravel-login-link","description":"","frontmatter":{},"headers":[],"relativePath":"packages/laravel-login-link.md","filePath":"packages/laravel-login-link.md","lastUpdated":1706064204000}'),l={name:"packages/laravel-login-link.md"},h=n(`

快速登录 spatie/laravel-login-link

在开发和测试中经常需要快速切换角色的用户,可以借助 spaite/laravel-login-link 来实现。

这个扩展包通过提供一个将呈现登录链接的组件来解决该问题。单击链接后,可以登录指定用户。

注意: 它适用于本地开发或测试阶段,不应该在任何线上可访问的环境中使用。

安装

通过 Composer 安装该软件包:

bash
composer require spatie/laravel-login-link

自定义配置

安装软件包后,如果需要发布配置文件,可以使用下面的命令:

bash
php artisan vendor:publish --tag="login-link-config"
php
use Spatie\\LoginLink\\Http\\Controllers\\LoginLinkController;
+import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=JSON.parse('{"title":"快速登录 spatie/laravel-login-link","description":"","frontmatter":{},"headers":[],"relativePath":"packages/laravel-login-link.md","filePath":"packages/laravel-login-link.md","lastUpdated":1706064204000}'),l={name:"packages/laravel-login-link.md"},h=n(`

快速登录 spatie/laravel-login-link

在开发和测试中经常需要快速切换角色的用户,可以借助 spaite/laravel-login-link 来实现。

这个扩展包通过提供一个将呈现登录链接的组件来解决该问题。单击链接后,可以登录指定用户。

注意: 它适用于本地开发或测试阶段,不应该在任何线上可访问的环境中使用。

安装

通过 Composer 安装该软件包:

bash
composer require spatie/laravel-login-link

自定义配置

安装软件包后,如果需要发布配置文件,可以使用下面的命令:

bash
php artisan vendor:publish --tag="login-link-config"
php
use Spatie\\LoginLink\\Http\\Controllers\\LoginLinkController;
 
 return [
     // 登录链接仅在这些环境中有效,一般可以设置为本地local、测试stage
diff --git a/assets/packages_laravel-login-link.md.JvVMGzDJ.lean.js b/assets/packages_laravel-login-link.md.Olxf7G32.lean.js
similarity index 100%
rename from assets/packages_laravel-login-link.md.JvVMGzDJ.lean.js
rename to assets/packages_laravel-login-link.md.Olxf7G32.lean.js
diff --git a/assets/partials_migrations.md.Tz41kgD7.js b/assets/partials_migrations.md.E0t3c2Hd.js
similarity index 98%
rename from assets/partials_migrations.md.Tz41kgD7.js
rename to assets/partials_migrations.md.E0t3c2Hd.js
index 4a97941ff..92dee8383 100644
--- a/assets/partials_migrations.md.Tz41kgD7.js
+++ b/assets/partials_migrations.md.E0t3c2Hd.js
@@ -27,7 +27,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const o=
 2014_10_12_000000_create_users_table ............................... [1] Ran
 2014_10_12_100000_create_password_reset_tokens_table ............... [1] Ran
 2019_08_19_000000_create_failed_jobs_table ......................... [1] Ran
-2019_12_14_000001_create_personal_access_tokens_table .............. [1] Ran

对存在表进行迁移

如果对现有表进行迁移,并且希望生成 Schema::table(),请在末尾添加_in_xxxxx_table_to_xxxxx_table,或指定 --table参数。

空迁移文件

bash
php artisan make:migration change_fields_products_table
+2019_12_14_000001_create_personal_access_tokens_table .............. [1] Ran

对存在表进行迁移

如果对现有表进行迁移,并且希望生成 Schema::table(),请在末尾添加_in_xxxxx_table_to_xxxxx_table,或指定 --table参数。

空迁移文件

bash
php artisan make:migration change_fields_products_table
 
 # INFO  Migration [database/migrations/2023_11_16_025034_change_fields_products_table.php] created successfully.
php
// database/migrations/2023_11_16_025034_change_fields_products_table.php
 return new class extends Migration
@@ -47,7 +47,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const o=
     {
         //
     }
-};

指定表

  • 方式一:使用 --table 参数指定表则会生成预填充 Schema::table('xxx', function() {}) 的类

    bash
    php artisan make:migration whatever_you_want --table=products
    +};

    指定表

    • 方式一:使用 --table 参数指定表则会生成预填充 Schema::table('xxx', function() {}) 的类

      bash
      php artisan make:migration whatever_you_want --table=products
       
       # INFO  Migration [database/migrations/2023_11_16_025540_whatever_you_want.php] created successfully.
      php
      // database/migrations/2023_11_16_025540_whatever_you_want.php
       return new class extends Migration
      @@ -71,7 +71,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const o=
                   //
               });
           }
      -};
    • 方式二:添加 in_xxxxx_table 语句

      bash
      php artisan make:migration change_fields_in_products_table
      +};
    • 方式二:添加 in_xxxxx_table 语句

      bash
      php artisan make:migration change_fields_in_products_table
       
       # INFO  Migration [database/migrations/2023_11_16_025304_change_fields_in_products_table.php] created successfully.
      php
      // database/migrations/2023_11_16_025304_change_fields_in_products_table.php
       return new class extends Migration
      diff --git a/assets/partials_migrations.md.Tz41kgD7.lean.js b/assets/partials_migrations.md.E0t3c2Hd.lean.js
      similarity index 100%
      rename from assets/partials_migrations.md.Tz41kgD7.lean.js
      rename to assets/partials_migrations.md.E0t3c2Hd.lean.js
      diff --git a/assets/partials_model.md.vO6Sq_p3.js b/assets/partials_model.md.dpslP7zF.js
      similarity index 99%
      rename from assets/partials_model.md.vO6Sq_p3.js
      rename to assets/partials_model.md.dpslP7zF.js
      index 582951819..50c9782f1 100644
      --- a/assets/partials_model.md.vO6Sq_p3.js
      +++ b/assets/partials_model.md.dpslP7zF.js
      @@ -265,7 +265,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
       Post::findOrFail($id)->tags()->orderByPivot('flag', 'desc')->get();

      查找单个记录

      sole() 方法将只返回一条符合条件的记录。

      • 如果没有找到这样的条目,则会抛出 NoRecordsFoundException

      • 如果找到多条记录,则会抛出 MultipleRecordsFoundException

      php
      DB::table('products')->where('ref', '#123')->sole();

      chuckMap 处理结果

      类似于 each() 方法,但更易于使用。自动将结果拆分为多个部分(块)。

      php
      return User::orderBy('name')->chunkMap(fn ($user) => [
           'id' => $user->id,
           'name' => $user->name,
      -]), 25);

      更新模型但不触发事件

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

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

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

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

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

      更新模型但不触发事件

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

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

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

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

      php
      use Illuminate\\Database\\Eloquent\\Model;
       use Illuminate\\Database\\Eloquent\\Prunable;
       class Flight extends Model
       {
      @@ -408,7 +408,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
           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
       {
      @@ -440,7 +440,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
               ->firstOr(function() {
                   // 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();

      通过模型访问器进行排序

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

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

      通过模型访问器进行排序

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

      php
      class User extends Model
       {
           // ...
           protected $appends = ['full_name'];
      @@ -477,7 +477,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
       } else {
           // 用户已存在并从数据库中获取
       }

      数据库驱动程序 Laravel Scout

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

      php
      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');  

      将数组传递给 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'
      @@ -552,7 +552,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
       $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(); // 更新数据库中的用户表中的记录和用户关联表中的电话号码记录
      php
      /**
      diff --git a/assets/partials_model.md.vO6Sq_p3.lean.js b/assets/partials_model.md.dpslP7zF.lean.js
      similarity index 100%
      rename from assets/partials_model.md.vO6Sq_p3.lean.js
      rename to assets/partials_model.md.dpslP7zF.lean.js
      diff --git a/assets/partials_testing.md.e6oc5ff9.js b/assets/partials_testing.md.fbu4V60w.js
      similarity index 98%
      rename from assets/partials_testing.md.e6oc5ff9.js
      rename to assets/partials_testing.md.fbu4V60w.js
      index 57615d549..cd2593c1d 100644
      --- a/assets/partials_testing.md.e6oc5ff9.js
      +++ b/assets/partials_testing.md.fbu4V60w.js
      @@ -12,7 +12,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                   $firstProduct->title,
                   $secondProduct->title,
               ]);
      -});

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

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

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

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

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

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

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

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

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

      php
      it('returns correct view', function() {
           // Act & Assert
           $this->get('/')
               ->assertOk()
      @@ -76,7 +76,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                       'description' => $anotherProduct->description,
                   ],
               ]);
      -});
      • assertJsonCount() 第二个参数支持传入指定键,比如 ->assertJsonCount(10, 'data')
      • assertJsonStructure() 支持使用 * 对数组进行匹配,比如:assertJsonStructure(['data' => ['*' => ['title', 'description']]])

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

      数据库 Database

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

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

      php
      // 该示例确保 post 请求成功并将数据正确的存储在数据库中。
      +});
      • assertJsonCount() 第二个参数支持传入指定键,比如 ->assertJsonCount(10, 'data')
      • assertJsonStructure() 支持使用 * 对数组进行匹配,比如:assertJsonStructure(['data' => ['*' => ['title', 'description']]])

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

      数据库 Database

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

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

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

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

      资源 Resources

      php
      // tests/Feature/Http/Resources/UsersResourceTest.php
      +});

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

      资源 Resources

      php
      // tests/Feature/Http/Resources/UsersResourceTest.php
       <?php
       
       use App\\Http\\Resources\\UsersResource;
      @@ -146,7 +146,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                   'created_at' => $this->resource->created_at->toDateTimeString(),
               ];
           }
      -}

      请求 Requests

      有时候需要单独测试自定义请求规则,可以直接对自定义请求类进行测试。

      php
      <?php
      +}

      请求 Requests

      有时候需要单独测试自定义请求规则,可以直接对自定义请求类进行测试。

      php
      <?php
       
       // tests\\Feature\\Http\\Requests\\SiteStoreRequestTest
       
      @@ -219,7 +219,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                   $fail('URL 必须包含协议,例如:http:// 或 https://');
               }
           }
      -}

      验证 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', [
      @@ -240,7 +240,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
       })->with([
           'title required' => [['description' => 'text'], ['title' => 'required']],
           'description required' => [['title' => 'Title'], ['description' => 'required']],
      -]);

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

      也可以在此基础上引入 RequestsFactories 请求工厂,更加规范的进行测试,详细内容可以查看这里

      自定义规则

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

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

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

      也可以在此基础上引入 RequestsFactories 请求工厂,更加规范的进行测试,详细内容可以查看这里

      自定义规则

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

      php
      it('has valid phone number for chinesePhoneNumber rule',
           fn ($value) => expect(new ChinesePhoneNumberRule())->toPassWith($value)
       )->with([
           [13800138000],
      @@ -264,7 +264,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                   $fail(__('validation.invalid_chinese_phone_number'));
               }
           }
      -}

      或者通过使用 Mockery::spy模拟验证。

      php
      <?php
      +}

      或者通过使用 Mockery::spy模拟验证。

      php
      <?php
       
       use App\\Rules\\PhoneNumber;
       
      @@ -335,7 +335,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
           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();
      @@ -347,7 +347,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
       });
      php
      // 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,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
           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();
      @@ -428,7 +428,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
           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
      @@ -466,7 +466,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
           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();
      @@ -495,7 +495,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
               ->expectsQuestion('Please provide the user ID of the user you want to merge', $userToBeMerged->id)
               ->expectsOutput('Accounts merged successfully')
               ->assertSuccessful(); // 可以期待输出并确保命令成功,这意味着退出代码为 0。
      -});

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

      测试视图 Views

      Laravel 10.x 支持使用命令创建视图。

      php
      <?php
      +});

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

      测试视图 Views

      Laravel 10.x 支持使用命令创建视图。

      php
      <?php
       // tests/Feature/View/Posts/IndexTest.php
       
       use App\\Models\\Post;
      @@ -516,7 +516,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
                   <li>{{ $post->name }}</li>
               @endforeach
           </ul>
      -</div>

      中间件 Middlewares

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

      php
      <?php
      +</div>

      中间件 Middlewares

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

      php
      <?php
       // tests/Unit/Http/Middleware/RedirectMiddlewareTest.php
       
       use App\\Models\\Redirect;
      @@ -698,7 +698,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
               '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',
      @@ -762,7 +762,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
               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();
       
      @@ -786,7 +786,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const F=
           }
       }

      架构测试 Architecture

      PEST 引入了一种称为架构测试的新型测试,这是一种测试应用程序架构并确保它遵循定义的代码规则,并且可以确保代码保持干净且可维护的好方法。

      php
      test('no forgotten debug statements')
           ->expect(['dd', 'dump', 'var_dump', 'ray'])
      -    ->not->toBeUsed();

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

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

      定时任务 Schedules

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

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

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

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

      定时任务 Schedules

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

      php
      <?php
       // App\\Console\\Kernel
       
       // ...
      diff --git a/assets/partials_testing.md.e6oc5ff9.lean.js b/assets/partials_testing.md.fbu4V60w.lean.js
      similarity index 100%
      rename from assets/partials_testing.md.e6oc5ff9.lean.js
      rename to assets/partials_testing.md.fbu4V60w.lean.js
      diff --git a/assets/partials_validation.md.xS4DbwrE.js b/assets/partials_validation.md.TinoEwuN.js
      similarity index 99%
      rename from assets/partials_validation.md.xS4DbwrE.js
      rename to assets/partials_validation.md.TinoEwuN.js
      index 596245d7b..5c34c5ff2 100644
      --- a/assets/partials_validation.md.xS4DbwrE.js
      +++ b/assets/partials_validation.md.TinoEwuN.js
      @@ -203,7 +203,7 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const y=
           {
               'prices.*.amount.required' => 'Please provide an amount for price #:position'
           }
      -}

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

      排除验证值

      当需要验证某个字段,但实际上并不需要它进行任何操作时,比如“接受条款和条件”,使用 exclude 规则。

      这样,调用验证的方法 validated 就不会返回它。

      php
      class UserStoreRequest extends FormRequest
      +}

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

      排除验证值

      当需要验证某个字段,但实际上并不需要它进行任何操作时,比如“接受条款和条件”,使用 exclude 规则。

      这样,调用验证的方法 validated 就不会返回它。

      php
      class UserStoreRequest extends FormRequest
       {
           public function rules(): array
           {
      @@ -227,4 +227,4 @@ import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const y=
       
       Validator::make(['color' => '#f00'], ['color' => 'hex_color'])->passes(); // true
       
      -Validator::make(['color' => '#ggg'], ['color' => 'hex_color'])->passes(); // false
      `,75),p=[l];function k(t,e,r,d,E,g){return a(),i("div",null,p)}const c=s(h,[["render",k]]);export{y as __pageData,c as default}; +Validator::make(['color' => '#ggg'], ['color' => 'hex_color'])->passes(); // false
`,75),p=[l];function k(t,e,d,r,E,g){return a(),i("div",null,p)}const c=s(h,[["render",k]]);export{y as __pageData,c as default}; diff --git a/assets/partials_validation.md.xS4DbwrE.lean.js b/assets/partials_validation.md.TinoEwuN.lean.js similarity index 85% rename from assets/partials_validation.md.xS4DbwrE.lean.js rename to assets/partials_validation.md.TinoEwuN.lean.js index e2df538a6..2a62e7a1b 100644 --- a/assets/partials_validation.md.xS4DbwrE.lean.js +++ b/assets/partials_validation.md.TinoEwuN.lean.js @@ -1 +1 @@ -import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const y=JSON.parse('{"title":"Validation 验证","description":"","frontmatter":{},"headers":[],"relativePath":"partials/validation.md","filePath":"partials/validation.md","lastUpdated":1701050197000}'),h={name:"partials/validation.md"},l=n("",75),p=[l];function k(t,e,r,d,E,g){return a(),i("div",null,p)}const c=s(h,[["render",k]]);export{y as __pageData,c as default}; +import{_ as s,c as i,o as a,V as n}from"./chunks/framework.HIcQKaVu.js";const y=JSON.parse('{"title":"Validation 验证","description":"","frontmatter":{},"headers":[],"relativePath":"partials/validation.md","filePath":"partials/validation.md","lastUpdated":1701050197000}'),h={name:"partials/validation.md"},l=n("",75),p=[l];function k(t,e,d,r,E,g){return a(),i("div",null,p)}const c=s(h,[["render",k]]);export{y as __pageData,c as default}; diff --git a/assets/partials_views.md.cI6Ea_JL.js b/assets/partials_views.md.Xvm8Qxt4.js similarity index 97% rename from assets/partials_views.md.cI6Ea_JL.js rename to assets/partials_views.md.Xvm8Qxt4.js index f984009f3..18d9bfd20 100644 --- a/assets/partials_views.md.cI6Ea_JL.js +++ b/assets/partials_views.md.Xvm8Qxt4.js @@ -10,7 +10,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y= <p>This is user {{ $user->id }}</p> @endforeach

$loop 变量还包含各种其他有用的属性:

属性描述
$loop->index当前循环迭代的索引(从 0 开始)。
$loop->iteration当前循环迭代(从 1 开始)。
$loop->remaining循环中剩余的迭代。
$loop->count正在迭代的数组中的项目总数。
$loop->first是否是循环的第一次迭代。
$loop->last是否是循环的最后一次迭代。
$loop->even是否是循环中的偶数迭代。
$loop->odd是否是循环中的奇数迭代。
$loop->depth当前循环的嵌套级别。
$loop->parent在嵌套循环中时,父循环变量。

官方文档 查看更多。

判断模版是否存在

可以在实际加载之前检查视图文件是否存在。

php
if (view()->exists('custom.page')) {
  // Load the view
-}

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

php
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\`
php
// 1. 路由定义
+}

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

php
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\`
php
// 1. 路由定义
 Route::get('about', [\\App\\Https\\Controllers\\PagesController::class, 'about']);
 
 // 2. 控制器
@@ -20,7 +20,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
     {
         return view('pages.about'); // 视图在 \`resources/pages/about.blade.php\`
     }
-}

@auth 模版指令

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

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

@auth 模版指令

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

php
@if(auth()->user())
 // 用户已验证身份
 @endif
php
@auth
 // 用户已验证身份
@@ -54,9 +54,9 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
 
 @unlessenabled('regular-registration')
 // 该应用程序不接受常规注册
-@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

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

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

IncludeIf, IncludeWhen, IncludeFirst 指令

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

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

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

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

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

php
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
 <x-post link="{{ $post->title }}"/>
 
 <!--使用 Blade-X 绑定变量-->
@@ -88,7 +88,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
 <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>
@@ -128,7 +128,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
 }
php
// 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 }}
@@ -144,7 +144,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
 </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>
@@ -170,9 +170,9 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const y=
 
 @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))/>
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' }}/>

@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>
php
<select name="country">
diff --git a/assets/partials_views.md.cI6Ea_JL.lean.js b/assets/partials_views.md.Xvm8Qxt4.lean.js
similarity index 100%
rename from assets/partials_views.md.cI6Ea_JL.lean.js
rename to assets/partials_views.md.Xvm8Qxt4.lean.js
diff --git a/assets/tips_db-models-and-eloquent.md.QeyCv8Q5.js b/assets/tips_db-models-and-eloquent.md.ZlfaD_0T.js
similarity index 99%
rename from assets/tips_db-models-and-eloquent.md.QeyCv8Q5.js
rename to assets/tips_db-models-and-eloquent.md.ZlfaD_0T.js
index 145a89101..971901039 100644
--- a/assets/tips_db-models-and-eloquent.md.QeyCv8Q5.js
+++ b/assets/tips_db-models-and-eloquent.md.ZlfaD_0T.js
@@ -27,7 +27,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
      ->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);
 }
@@ -38,7 +38,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
 }
php
public function scopePublished($query)
 {
     return $query->where('is_published', true);
-}

多个查询范围

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

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

多个查询范围

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

php
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
     return $query->where('active', 1);
 }
  
@@ -48,7 +48,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
     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()
     {
@@ -75,7 +75,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
 $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');
@@ -115,7 +115,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
 {
     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'),
@@ -164,7 +164,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
     }
 }

groupBy 按首字母分组

可以在 groupBy 接收自定义回调中按任何自定义条件对查询结果进行分组,以下是如何按公司名的首字母进行分组

php
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
 {
@@ -195,7 +195,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
 User::find([1,2,3], ['first_name', 'email']);

whereKey 按主键查找

使用 whereKey() 方法查找多个记录,该方法负责确定哪个字段正是您的主键(id 是默认值,但可以在 Eloquent 模型中覆盖它)

php
User::whereKey([1, 2, 3])->get();

使用 UUID 代替自动递增

在模型中使用自动递增 ID。

迁移文件:

php
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
@@ -254,7 +254,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
     }
 }

DB::statement() 查询方式

如果需要执行一个简单的 SQL 查询,但没有得到任何结果。

比如更改数据库中的某些内容,可以只执行 DB::statement()

php
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]
 );
php
Flight::where('departure', 'Oakland')
@@ -420,7 +420,7 @@ import{_ as s,c as i,o as a,V as h}from"./chunks/framework.HIcQKaVu.js";const F=
     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.QeyCv8Q5.lean.js b/assets/tips_db-models-and-eloquent.md.ZlfaD_0T.lean.js
similarity index 100%
rename from assets/tips_db-models-and-eloquent.md.QeyCv8Q5.lean.js
rename to assets/tips_db-models-and-eloquent.md.ZlfaD_0T.lean.js
diff --git a/assets/tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.js b/assets/tips_optimize-factory-database-batch-insert.md.f82qCgz_.js
similarity index 98%
rename from assets/tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.js
rename to assets/tips_optimize-factory-database-batch-insert.md.f82qCgz_.js
index 6720d0b58..5fdfdc6d9 100644
--- a/assets/tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.js
+++ b/assets/tips_optimize-factory-database-batch-insert.md.f82qCgz_.js
@@ -1,4 +1,4 @@
-import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const h="/laravel-study/assets/speed-comparison-preview.BrhC4Axj.png",o=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}'),n={name:"tips/optimize-factory-database-batch-insert.md"},k=t(`

优化 Factory 数据库批量插入

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

php
// 如果使用这种方式批量写入大量测试数据,建议采用下面的方式批量插入数据库记录。
+import{_ as s,c as i,o as a,V as t}from"./chunks/framework.HIcQKaVu.js";const h="/laravel-study/assets/speed-comparison-preview.BrhC4Axj.png",o=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}'),n={name:"tips/optimize-factory-database-batch-insert.md"},k=t(`

优化 Factory 数据库批量插入

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

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

具体代码查看仓库地址github.com/curder/laravel-tips

执行速度对比

php
// Before
diff --git a/assets/tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.lean.js b/assets/tips_optimize-factory-database-batch-insert.md.f82qCgz_.lean.js
similarity index 100%
rename from assets/tips_optimize-factory-database-batch-insert.md.zhKOSvRZ.lean.js
rename to assets/tips_optimize-factory-database-batch-insert.md.f82qCgz_.lean.js
diff --git a/assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.js b/assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.js
similarity index 76%
rename from assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.js
rename to assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.js
index b8f1342c4..de0c279b2 100644
--- a/assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.js
+++ b/assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.js
@@ -1,3 +1,3 @@
-import{_ as e,c as a,o as t,V as s}from"./chunks/framework.HIcQKaVu.js";const _=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1700190096000}'),i={name:"tips/reuse-the-environment-variable-value.md"},n=s(`

重用环境变量值

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

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

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

重用环境变量值

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

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

txt
APP_URL=https://laravel-tips.test
 ADMIN_URL=https://laravel-tips.test
txt
APP_URL=https://laravel-tips.test
-ADMIN_URL="\${APP_URL}"
`,4),p=[n];function l(o,r,c,d,h,v){return t(),a("div",null,p)}const b=e(i,[["render",l]]);export{_ as __pageData,b as default}; +ADMIN_URL="\${APP_URL}"
`,4),n=[i];function l(o,r,c,d,v,h){return t(),a("div",null,n)}const b=e(p,[["render",l]]);export{_ as __pageData,b as default}; diff --git a/assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.lean.js b/assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.lean.js similarity index 62% rename from assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.lean.js rename to assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.lean.js index b308ea7cd..bd93e1024 100644 --- a/assets/tips_reuse-the-environment-variable-value.md.aGGykNAC.lean.js +++ b/assets/tips_reuse-the-environment-variable-value.md.9X_QhAK_.lean.js @@ -1 +1 @@ -import{_ as e,c as a,o as t,V as s}from"./chunks/framework.HIcQKaVu.js";const _=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1700190096000}'),i={name:"tips/reuse-the-environment-variable-value.md"},n=s("",4),p=[n];function l(o,r,c,d,h,v){return t(),a("div",null,p)}const b=e(i,[["render",l]]);export{_ as __pageData,b as default}; +import{_ as e,c as a,o as t,V as s}from"./chunks/framework.HIcQKaVu.js";const _=JSON.parse('{"title":"重用环境变量值","description":"","frontmatter":{},"headers":[],"relativePath":"tips/reuse-the-environment-variable-value.md","filePath":"tips/reuse-the-environment-variable-value.md","lastUpdated":1700190096000}'),p={name:"tips/reuse-the-environment-variable-value.md"},i=s("",4),n=[i];function l(o,r,c,d,v,h){return t(),a("div",null,n)}const b=e(p,[["render",l]]);export{_ as __pageData,b as default}; diff --git a/collections/all.html b/collections/all.html index 3dd815549..0c9d90426 100644 --- a/collections/all.html +++ b/collections/all.html @@ -12,7 +12,7 @@ - + @@ -21,7 +21,7 @@
Skip to content

all

该方法返回该集合表示的底层数组

php
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();
 
 /**
@@ -42,7 +42,7 @@
  [1, 2, 3, 4],
 ]
 */

关联方法

- + \ No newline at end of file diff --git a/collections/avg.html b/collections/avg.html index 890c7cf9c..6ba8d6e35 100644 --- a/collections/avg.html +++ b/collections/avg.html @@ -12,13 +12,13 @@ - + -
Skip to content

avg

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

一些示例

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

avg

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

一些示例

php
// 获取一维数组
 collect([10, 20, 30])->average(); // 20
 
 // 获取二维数组的平均值
@@ -44,7 +44,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 00325693f..a5cafc2fa 100644 --- a/collections/chunk.html +++ b/collections/chunk.html @@ -12,13 +12,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: [
@@ -46,7 +46,7 @@
      ],
    }
 */

相关方法

- + \ No newline at end of file diff --git a/collections/chunkWhile.html b/collections/chunkWhile.html index 36f03178f..d2d4987f3 100644 --- a/collections/chunkWhile.html +++ b/collections/chunkWhile.html @@ -23,7 +23,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 dcc6108e5..5eec1a9c3 100644 --- a/collections/collapse.html +++ b/collections/collapse.html @@ -12,13 +12,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]
 
@@ -29,7 +29,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 0583099d3..9061f8031 100644 --- a/collections/collect.html +++ b/collections/collect.html @@ -31,7 +31,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 9be7d1f17..48a0891f3 100644 --- a/collections/combine.html +++ b/collections/combine.html @@ -25,7 +25,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 711d7fd07..383e5bd25 100644 --- a/collections/concat.html +++ b/collections/concat.html @@ -26,7 +26,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 d3ecc388a..63706f1fa 100644 --- a/collections/contains.html +++ b/collections/contains.html @@ -12,13 +12,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
php
$collection = collect([
   ['product' => 'Desk', 'price' => 200],
@@ -31,7 +31,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 a03cdff51..b3858fec3 100644 --- a/collections/containsOneItem.html +++ b/collections/containsOneItem.html @@ -23,7 +23,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 098a313de..bc7848c8a 100644 --- a/collections/containsStrict.html +++ b/collections/containsStrict.html @@ -22,7 +22,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 711f44834..1caaedac0 100644 --- a/collections/count.html +++ b/collections/count.html @@ -19,7 +19,7 @@
Skip to content

count

返回该集合内的项目总数

php
collect([1, 2, 3, 4])->count(); // 4
- + \ No newline at end of file diff --git a/collections/countBy.html b/collections/countBy.html index 294084884..511311f27 100644 --- a/collections/countBy.html +++ b/collections/countBy.html @@ -12,18 +12,18 @@ - + -
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]
php
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 7fccbea48..5f7a05798 100644 --- a/collections/crossJoin.html +++ b/collections/crossJoin.html @@ -41,7 +41,7 @@ [2, "b", "d"] ] */
- + \ No newline at end of file diff --git a/collections/dd.html b/collections/dd.html index d5ef8c32b..70d492644 100644 --- a/collections/dd.html +++ b/collections/dd.html @@ -32,7 +32,7 @@ 22 => 12 ] */

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

相关方法

- + \ No newline at end of file diff --git a/collections/diff.html b/collections/diff.html index 3b65b1919..8c32d804c 100644 --- a/collections/diff.html +++ b/collections/diff.html @@ -21,7 +21,7 @@
Skip to content

diff

将集合与其它集合或纯 PHP 数组进行值的比较,然后返回原集合中存在而给定集合中不存在的值,求差集。

求差集

php
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 8bf8a3c1f..62905c4ea 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"]

相关方法

- + \ No newline at end of file diff --git a/collections/diffAssocUsing.html b/collections/diffAssocUsing.html index 8ac7d9cbd..533c349e9 100644 --- a/collections/diffAssocUsing.html +++ b/collections/diffAssocUsing.html @@ -30,7 +30,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 0eb094a36..d6ba326f8 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"]

相关方法

- + \ No newline at end of file diff --git a/collections/diffKeysUsing.html b/collections/diffKeysUsing.html index f4369d8f4..d81225446 100644 --- a/collections/diffKeysUsing.html +++ b/collections/diffKeysUsing.html @@ -30,7 +30,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 c1ad3d430..f7e8b40ec 100644 --- a/collections/diffUsing.html +++ b/collections/diffUsing.html @@ -31,7 +31,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 9c8323852..a9c2375e6 100644 --- a/collections/doesntContain.html +++ b/collections/doesntContain.html @@ -25,7 +25,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 cb89c4b6b..9652e0f34 100644 --- a/collections/dump.html +++ b/collections/dump.html @@ -25,7 +25,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 252c4ccac..be323e6c8 100644 --- a/collections/duplicates.html +++ b/collections/duplicates.html @@ -24,7 +24,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 678f1fba6..411033d9f 100644 --- a/collections/duplicatesStrict.html +++ b/collections/duplicatesStrict.html @@ -33,7 +33,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 1879670af..60b1d53f5 100644 --- a/collections/each.html +++ b/collections/each.html @@ -51,7 +51,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 ab9ce6865..bea2873cf 100644 --- a/collections/eachSpread.html +++ b/collections/eachSpread.html @@ -40,7 +40,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 fc59e29b3..2b461fa7b 100644 --- a/collections/every.html +++ b/collections/every.html @@ -19,7 +19,7 @@
Skip to content

every

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

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

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

php
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 ae29cb694..8ab4e2255 100644 --- a/collections/examples/README.html +++ b/collections/examples/README.html @@ -19,7 +19,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 9ba5a1c15..627010ec3 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 @@ -83,7 +83,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 fd669485f..79b50f2be 100644 --- a/collections/examples/format-github-events-score.html +++ b/collections/examples/format-github-events-score.html @@ -12,7 +12,7 @@ - + @@ -44,7 +44,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()
 );
 
@@ -96,7 +96,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()
 );
 
@@ -129,7 +129,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 17d7b45e5..b1d6a1ce3 100644 --- a/collections/examples/get-the-corresponding-key-by-value.html +++ b/collections/examples/get-the-corresponding-key-by-value.html @@ -31,7 +31,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 123c935eb..8e7b9348e 100644 --- a/collections/examples/map-format.html +++ b/collections/examples/map-format.html @@ -105,7 +105,7 @@ ], } */ - + \ No newline at end of file diff --git a/collections/examples/markdown-format.html b/collections/examples/markdown-format.html index e99e18d58..619dbb5c1 100644 --- a/collections/examples/markdown-format.html +++ b/collections/examples/markdown-format.html @@ -62,7 +62,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 7ffd1aaba..ea98e049f 100644 --- a/collections/examples/order-info-summary.html +++ b/collections/examples/order-info-summary.html @@ -12,7 +12,7 @@ - + @@ -75,14 +75,14 @@ 'qty' => 3, 'customer_name'=>'Mandy', ], -];
php
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
+];
php
collect($orders)->groupBy('date');
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->groupBy('supplier')
 );
php
collect($orders)->groupBy('date')->map(
     fn ($item) => $item->sum(
         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 5cd49fa69..206fa4e80 100644 --- a/collections/examples/using-reduce-create-lookup-array.html +++ b/collections/examples/using-reduce-create-lookup-array.html @@ -12,7 +12,7 @@ - + @@ -38,7 +38,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"]
php
$emails = [];
 foreach ($employees as $key => $value) {
@@ -52,7 +52,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 1692ef90e..10157e068 100644 --- a/collections/examples/using-sum-method.html +++ b/collections/examples/using-sum-method.html @@ -60,7 +60,7 @@ ->sum();

使用 flatMapsum

php
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 9fd3941ee..eb90837d6 100644 --- a/collections/except.html +++ b/collections/except.html @@ -24,7 +24,7 @@ 'discount', 'name' ]); // ["product_id" => 1]

与之相反操作是 only 方法。

相关方法

- + \ No newline at end of file diff --git a/collections/filter.html b/collections/filter.html index 7f2589593..8532f0660 100644 --- a/collections/filter.html +++ b/collections/filter.html @@ -23,7 +23,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 b1399200a..9d1153b6a 100644 --- a/collections/first.html +++ b/collections/first.html @@ -12,17 +12,17 @@ - + -
Skip to content

first

返回集合中第一个元素

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

first

返回集合中第一个元素

php
collect([1, 2, 3, 4])->first(); // 1
php
// 从集合左往右遍历,满足条件元素被返回。
 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

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

其它方法

- + \ No newline at end of file diff --git a/collections/firstOrFail.html b/collections/firstOrFail.html index 69ee08706..51f3e153a 100644 --- a/collections/firstOrFail.html +++ b/collections/firstOrFail.html @@ -24,7 +24,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 c8a8e9711..1d49b172f 100644 --- a/collections/firstWhere.html +++ b/collections/firstWhere.html @@ -12,13 +12,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],
@@ -36,7 +36,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 1327524fb..1c504f60c 100644 --- a/collections/flatMap.html +++ b/collections/flatMap.html @@ -25,7 +25,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 655267d1d..4296c10ad 100644 --- a/collections/flatten.html +++ b/collections/flatten.html @@ -31,7 +31,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 e3f70c836..0460d1a15 100644 --- a/collections/flip.html +++ b/collections/flip.html @@ -21,7 +21,7 @@
Skip to content

flip

将集合中的键和对应的数值进行互换

php
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 e2b072353..c3abed0c7 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]
  • 参数一:当前页面
  • 参数二:每页显示条目数
- + \ No newline at end of file diff --git a/collections/forget.html b/collections/forget.html index 35c2c3df8..1f4271bd8 100644 --- a/collections/forget.html +++ b/collections/forget.html @@ -28,7 +28,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 4dc49390e..61741f397 100644 --- a/collections/get.html +++ b/collections/get.html @@ -12,13 +12,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"
php
collect(['name' => 'taylor', 'framework' => 'laravel'])
     ->get('foo', 'bar'); // bar
php
// 如果指定的键不存在,会调用回调
 collect(['name' => 'taylor', 'framework' => 'laravel'])
@@ -29,7 +29,7 @@
             return 'bar';
         }
     ); // bar

相关方法

- + \ No newline at end of file diff --git a/collections/groupBy.html b/collections/groupBy.html index 0fe82a4c4..544dd047a 100644 --- a/collections/groupBy.html +++ b/collections/groupBy.html @@ -104,7 +104,7 @@ ] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/has.html b/collections/has.html index e6a8970fb..e8cfc7dc5 100644 --- a/collections/has.html +++ b/collections/has.html @@ -23,7 +23,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 983d8389a..6dfc38c2f 100644 --- a/collections/hasAny.html +++ b/collections/hasAny.html @@ -22,7 +22,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 842e6b34d..1112c7c39 100644 --- a/collections/implode.html +++ b/collections/implode.html @@ -22,7 +22,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"

相关方法

- + \ No newline at end of file diff --git a/collections/index.html b/collections/index.html index 0246744a0..89bff6bb0 100644 --- a/collections/index.html +++ b/collections/index.html @@ -26,7 +26,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 11d436bb2..220a98924 100644 --- a/collections/intersect.html +++ b/collections/intersect.html @@ -22,7 +22,7 @@ ->intersect(['Desk', 'Chair', 'Bookcase']); // [ "Desk", "Chair"]

不改变原数组或集合。

相关方法

- + \ No newline at end of file diff --git a/collections/intersectByKeys.html b/collections/intersectByKeys.html index dcae7d80d..e5be9f1c3 100644 --- a/collections/intersectByKeys.html +++ b/collections/intersectByKeys.html @@ -27,7 +27,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 0a496971a..501c60345 100644 --- a/collections/isEmpty.html +++ b/collections/isEmpty.html @@ -26,7 +26,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 1343924d0..5b7690eec 100644 --- a/collections/isNotEmpty.html +++ b/collections/isNotEmpty.html @@ -23,7 +23,7 @@ collect([1, 2, 3, 4])->isNotEmpty(); // true

isNotEmpty 方法不会检查集合中的元素的类型,仅仅检查集合是否为空。

比如:集合中有且仅有 null, [], '', 0, false 等元素的时候,返回值依然是 false

php
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 a9349d407..6b111cdf6 100644 --- a/collections/join.html +++ b/collections/join.html @@ -23,7 +23,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 1a0674c4b..3bf636210 100644 --- a/collections/keyBy.html +++ b/collections/keyBy.html @@ -39,7 +39,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 81fb080f5..b571205d3 100644 --- a/collections/keys.html +++ b/collections/keys.html @@ -24,7 +24,7 @@ ])->keys(); // ["prod-100", "prod-200"]

相关方法

- + \ No newline at end of file diff --git a/collections/last.html b/collections/last.html index a8e95ef3b..400ab28d7 100644 --- a/collections/last.html +++ b/collections/last.html @@ -21,7 +21,7 @@
Skip to content

last

返回集合中通过给定真实测试的最后一个元素,不是一个新集合

不传入参数调用 last 方法来获取集合中最后一个元素。如果集合是空的,返回 null

php
collect([1, 2, 3, 4])->last(); // 4

使用回调

从集合右往左遍历,满足条件元素被返回。

php
collect([1, 2, 3, 4])->last(fn ($element) => $element < 2); // 1

使用默认值

last 方法允许传递一个默认值,当通过回调函数遍历集合没有返回值时,默认值将会被返回。

php
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 5bceecd3c..2f3eac5b4 100644 --- a/collections/lazy.html +++ b/collections/lazy.html @@ -27,7 +27,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 85ae17eac..e9ee6594d 100644 --- a/collections/macro.html +++ b/collections/macro.html @@ -34,7 +34,7 @@ }); collect(['first', 'second'])->toLocale('es');

相关方法

- + \ No newline at end of file diff --git a/collections/make.html b/collections/make.html index e8c056bd6..31b160949 100644 --- a/collections/make.html +++ b/collections/make.html @@ -24,7 +24,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 42d29d71a..03115573d 100644 --- a/collections/map.html +++ b/collections/map.html @@ -41,7 +41,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 b90bb5179..1cf96499d 100644 --- a/collections/mapInto.html +++ b/collections/mapInto.html @@ -38,7 +38,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 015c95319..3bf396769 100644 --- a/collections/mapSpread.html +++ b/collections/mapSpread.html @@ -38,7 +38,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 7bf485b98..aa939b59b 100644 --- a/collections/mapToDictionary.html +++ b/collections/mapToDictionary.html @@ -28,7 +28,7 @@ ); // ["apples" => [59, 69], "bananas" => [54, 94]]

相关方法

- + \ No newline at end of file diff --git a/collections/mapToGroups.html b/collections/mapToGroups.html index 4f60e79c3..5e841c0ae 100644 --- a/collections/mapToGroups.html +++ b/collections/mapToGroups.html @@ -49,7 +49,7 @@ ["product" => "bananas", "price" => 94] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/mapWithKeys.html b/collections/mapWithKeys.html index 7546b8f41..3b8e64d16 100644 --- a/collections/mapWithKeys.html +++ b/collections/mapWithKeys.html @@ -55,7 +55,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 bde60b42f..12f601e11 100644 --- a/collections/max.html +++ b/collections/max.html @@ -45,7 +45,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 cf4137e82..87c01e9a0 100644 --- a/collections/median.html +++ b/collections/median.html @@ -25,7 +25,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 0de488237..a5e58b3f6 100644 --- a/collections/merge.html +++ b/collections/merge.html @@ -27,7 +27,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 1fe9cf8ea..dcfe7203a 100644 --- a/collections/mergeRecursive.html +++ b/collections/mergeRecursive.html @@ -31,7 +31,7 @@ "discount" => false, ] */

相关方法

- + \ No newline at end of file diff --git a/collections/min.html b/collections/min.html index 510f2a526..00b8672a3 100644 --- a/collections/min.html +++ b/collections/min.html @@ -44,7 +44,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 26f7e0cef..ef762d71e 100644 --- a/collections/mode.html +++ b/collections/mode.html @@ -25,7 +25,7 @@ ['foo' => 40] ])->mode('foo'); // [10] - + \ No newline at end of file diff --git a/collections/nth.html b/collections/nth.html index adf95161e..31564982e 100644 --- a/collections/nth.html +++ b/collections/nth.html @@ -28,7 +28,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 46880d9b4..6c9bf7b1e 100644 --- a/collections/only.html +++ b/collections/only.html @@ -40,7 +40,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 f55947c7d..62963d8a8 100644 --- a/collections/pad.html +++ b/collections/pad.html @@ -26,7 +26,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 dfd88b8d4..28caffe3d 100644 --- a/collections/partition.html +++ b/collections/partition.html @@ -23,7 +23,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 98da5e03c..7d8e5934c 100644 --- a/collections/pipe.html +++ b/collections/pipe.html @@ -26,7 +26,7 @@ # 类似于直接调用 sum 方法 collect([1, 2, 3])->sum();

相关方法

- + \ No newline at end of file diff --git a/collections/pipeInto.html b/collections/pipeInto.html index cdb9c0fed..3c49face7 100644 --- a/collections/pipeInto.html +++ b/collections/pipeInto.html @@ -36,7 +36,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 07a72648c..397c73b5b 100644 --- a/collections/pipeThrough.html +++ b/collections/pipeThrough.html @@ -26,7 +26,7 @@ ]); // 15

相关方法

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

相关方法

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

相关方法

- + \ No newline at end of file diff --git a/collections/prepend.html b/collections/prepend.html index 3d54a5a6b..3e36d3c49 100644 --- a/collections/prepend.html +++ b/collections/prepend.html @@ -27,7 +27,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 45eaaeada..bf7c7df7f 100644 --- a/collections/pull.html +++ b/collections/pull.html @@ -23,7 +23,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 39b83060a..d241fd4f9 100644 --- a/collections/push.html +++ b/collections/push.html @@ -23,7 +23,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 71f671a1b..95061ca63 100644 --- a/collections/put.html +++ b/collections/put.html @@ -23,7 +23,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 4c157e236..1cbc8d42d 100644 --- a/collections/random.html +++ b/collections/random.html @@ -23,7 +23,7 @@ // 4 - (retrieved randomly)

可以选择性传入一个整数到 random 来指定要获取的随机项的数量。

当显式传递希望接收的数量时,则会返回指定数量项目的集合。

php
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 57e9c44bb..07f862ba3 100644 --- a/collections/reduce.html +++ b/collections/reduce.html @@ -36,7 +36,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 44ac9b73a..b26f05f96 100644 --- a/collections/reduceSpread.html +++ b/collections/reduceSpread.html @@ -22,7 +22,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 e6fe2826f..3eb9aece8 100644 --- a/collections/reject.html +++ b/collections/reject.html @@ -22,7 +22,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 e358e1629..81c16f026 100644 --- a/collections/replace.html +++ b/collections/replace.html @@ -21,7 +21,7 @@
Skip to content

replace

通过指定格式替换集合元素。

替换方法的行为与 merge 类似;除了覆盖具有字符串键的匹配项之外,replace 方法还可以通过指定对应的键覆盖集合元素。

php
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 f99c9ddbb..eadcafb9d 100644 --- a/collections/replaceRecursive.html +++ b/collections/replaceRecursive.html @@ -32,7 +32,7 @@ ]); // ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

相关方法

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

相关方法

- + \ No newline at end of file diff --git a/collections/search.html b/collections/search.html index 0464431ac..f8aa495f8 100644 --- a/collections/search.html +++ b/collections/search.html @@ -21,7 +21,7 @@
Skip to content
- + \ No newline at end of file diff --git a/collections/shift.html b/collections/shift.html index be76298e6..774ab5acd 100644 --- a/collections/shift.html +++ b/collections/shift.html @@ -23,7 +23,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 8acfcf729..55a5030b2 100644 --- a/collections/shuffle.html +++ b/collections/shuffle.html @@ -21,7 +21,7 @@
Skip to content

shuffle

随机排序集合中的项目。

php
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 91815cae1..a8757dfd5 100644 --- a/collections/skip.html +++ b/collections/skip.html @@ -21,7 +21,7 @@
Skip to content

skip

方法返回一个新集合,从集合的开头删除给定数量的元素。

php
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 2f72f497f..46b9b75ad 100644 --- a/collections/skipUntil.html +++ b/collections/skipUntil.html @@ -23,7 +23,7 @@ // [2 => 3, 3 => 4]

自定义回调

php
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 d0f9bc7da..78d691571 100644 --- a/collections/skipWhile.html +++ b/collections/skipWhile.html @@ -21,7 +21,7 @@
Skip to content

skipWhile

跳过集合中的项目,同时给定的回调返回 true ,然后将集合中的其余项目作为新集合返回。

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

自定义回调

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

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

php
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 0d1b75917..e4c10573c 100644 --- a/collections/slice.html +++ b/collections/slice.html @@ -29,7 +29,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 e70557e73..3631a738f 100644 --- a/collections/sliding.html +++ b/collections/sliding.html @@ -24,7 +24,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 0e71a454e..3b07e205a 100644 --- a/collections/sole.html +++ b/collections/sole.html @@ -30,7 +30,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 1c688de36..79d714685 100644 --- a/collections/sort.html +++ b/collections/sort.html @@ -28,7 +28,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 f230153a5..b95f7b3e7 100644 --- a/collections/sortBy.html +++ b/collections/sortBy.html @@ -49,7 +49,7 @@ ])->sortBy( fn ($item) => array_search($item, $fields) );

相关方法

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

相关方法

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

相关方法

- + \ No newline at end of file diff --git a/collections/sortKeys.html b/collections/sortKeys.html index e191b0b14..914dd365f 100644 --- a/collections/sortKeys.html +++ b/collections/sortKeys.html @@ -21,7 +21,7 @@
Skip to content

sortKeys

按底层关联数组的键对集合进行排序

php
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 b0a8677fb..1da7ab095 100644 --- a/collections/sortKeysDesc.html +++ b/collections/sortKeysDesc.html @@ -21,7 +21,7 @@
Skip to content

sortKeysDesc

按底层关联数组的键对集合进行倒序排序

php
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 f73d77053..bb047fbd3 100644 --- a/collections/sortKeysUsing.html +++ b/collections/sortKeysUsing.html @@ -25,7 +25,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 3ebf20851..e692de28d 100644 --- a/collections/splice.html +++ b/collections/splice.html @@ -49,7 +49,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 d65382877..e4f306476 100644 --- a/collections/split.html +++ b/collections/split.html @@ -21,7 +21,7 @@
Skip to content

split

将集合按给定的值拆分

php
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 df9d0816a..5b1a3b879 100644 --- a/collections/splitIn.html +++ b/collections/splitIn.html @@ -21,7 +21,7 @@
Skip to content

splitIn

将集合分为给定数量的组。

php
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 64017292d..2efbf9923 100644 --- a/collections/sum.html +++ b/collections/sum.html @@ -32,7 +32,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 aa4db300d..f111db563 100644 --- a/collections/take.html +++ b/collections/take.html @@ -28,7 +28,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 a800b102f..8056479c1 100644 --- a/collections/takeUntil.html +++ b/collections/takeUntil.html @@ -24,7 +24,7 @@ // [1, 2]

也可以将简单的值传递给 takeUntil 方法以获取项目,直到找到给定的值。

php
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 9edc2db2c..1ec7b7586 100644 --- a/collections/takeWhile.html +++ b/collections/takeWhile.html @@ -22,7 +22,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 30ca05d07..fbe77953b 100644 --- a/collections/tap.html +++ b/collections/tap.html @@ -26,7 +26,7 @@ ->shift(); // 1

相关方法

- + \ No newline at end of file diff --git a/collections/times.html b/collections/times.html index 146099fb1..4ef71bbe9 100644 --- a/collections/times.html +++ b/collections/times.html @@ -23,7 +23,7 @@ // [3, 6, 9]

使用这个方法可以与工厂结合使用创建出 Eloquent 模型

php
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 30d8c1ce2..3fa061414 100644 --- a/collections/toArray.html +++ b/collections/toArray.html @@ -21,7 +21,7 @@
Skip to content

toArray

将集合转换成 PHP 数组。如果集合的值是 Eloquent 模型,那也会被转换成数组。

php
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 f33a1e9ec..c8a0e4aaa 100644 --- a/collections/toJson.html +++ b/collections/toJson.html @@ -26,7 +26,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 a33bd15d4..d7dcede3a 100644 --- a/collections/transform.html +++ b/collections/transform.html @@ -22,7 +22,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 2bf0274df..5aa838d65 100644 --- a/collections/undot.html +++ b/collections/undot.html @@ -43,7 +43,7 @@ ] ] */ - + \ No newline at end of file diff --git a/collections/union.html b/collections/union.html index 9a1b4b1db..860c3683b 100644 --- a/collections/union.html +++ b/collections/union.html @@ -22,7 +22,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 b4b87a0d7..22cf2295f 100644 --- a/collections/unique.html +++ b/collections/unique.html @@ -49,7 +49,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 e4df6a154..0a3fb1685 100644 --- a/collections/uniqueStrict.html +++ b/collections/uniqueStrict.html @@ -45,7 +45,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 9c2de1251..3938b30e7 100644 --- a/collections/unless.html +++ b/collections/unless.html @@ -23,7 +23,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 6f3b1a1fd..20bf40c34 100644 --- a/collections/unwrap.html +++ b/collections/unwrap.html @@ -23,7 +23,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 f74c21790..a89a53d89 100644 --- a/collections/value.html +++ b/collections/value.html @@ -24,7 +24,7 @@ ])->value('price'); // 200

相关方法

- + \ No newline at end of file diff --git a/collections/values.html b/collections/values.html index 6c7ded7e6..e2c973252 100644 --- a/collections/values.html +++ b/collections/values.html @@ -29,7 +29,7 @@ ["product" => "Desk", "price" => 200] ] */

相关方法

- + \ No newline at end of file diff --git a/collections/when.html b/collections/when.html index b2180a1f5..9342620ed 100644 --- a/collections/when.html +++ b/collections/when.html @@ -23,7 +23,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 165e79b14..279b53cfd 100644 --- a/collections/whenEmpty.html +++ b/collections/whenEmpty.html @@ -30,7 +30,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 426cae9ad..5179567b5 100644 --- a/collections/whenNotEmpty.html +++ b/collections/whenNotEmpty.html @@ -29,7 +29,7 @@ ); // ["curder"]

相关方法

- + \ No newline at end of file diff --git a/collections/where.html b/collections/where.html index 924b4afff..c2206bcb3 100644 --- a/collections/where.html +++ b/collections/where.html @@ -43,7 +43,7 @@ ["product" => "coconuts", "price" => 80], ] */

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

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

相关方法

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

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

相关方法

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

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

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

相关方法

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

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

相关方法

- + \ No newline at end of file diff --git a/collections/whereInstanceOf.html b/collections/whereInstanceOf.html index 116f9f068..61dacd27b 100644 --- a/collections/whereInstanceOf.html +++ b/collections/whereInstanceOf.html @@ -25,7 +25,7 @@ ->whereInstanceOf(Post::class); // [2 => Post]

相关方法

- + \ No newline at end of file diff --git a/collections/whereNotBetween.html b/collections/whereNotBetween.html index 3e57da39d..2c57436ae 100644 --- a/collections/whereNotBetween.html +++ b/collections/whereNotBetween.html @@ -26,7 +26,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 665d3aae4..154617d0f 100644 --- a/collections/whereNotIn.html +++ b/collections/whereNotIn.html @@ -31,7 +31,7 @@ ["product" => "banners", "price" => 70] ] */

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

相关方法

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

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

相关方法

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

相关方法

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

相关方法

- + \ No newline at end of file diff --git a/collections/whereStrict.html b/collections/whereStrict.html index 5bfbcb734..f1d2150b8 100644 --- a/collections/whereStrict.html +++ b/collections/whereStrict.html @@ -33,7 +33,7 @@ ])->whereStrict('price', '>', '50'); // []

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

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

相关方法

- + \ No newline at end of file diff --git a/collections/wrap.html b/collections/wrap.html index 2798d5643..7eaa6241a 100644 --- a/collections/wrap.html +++ b/collections/wrap.html @@ -23,7 +23,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 c966d6a04..228e33f9a 100644 --- a/collections/zip.html +++ b/collections/zip.html @@ -55,7 +55,7 @@ [4, 8, "b"] ] */ - + \ No newline at end of file diff --git a/hashmap.json b/hashmap.json index 65d80598c..a2b4ac606 100644 --- a/hashmap.json +++ b/hashmap.json @@ -1 +1 @@ -{"collections_chunk.md":"aauTVJbv","collections_crossjoin.md":"-R0sMNmR","collections_all.md":"X8pPdG0Q","collections_chunkwhile.md":"Eld99fPB","collections_collapse.md":"leJkU4Xb","collections_dd.md":"_oeIlJJ4","collections_contains.md":"_c9S_erV","collections_combine.md":"2vPAOnff","collections_count.md":"iQwti93y","collections_diffassoc.md":"u_qdxAr0","collections_examples_readme.md":"eCrhk73W","collections_examples_markdown-format.md":"qABRGspv","collections_examples_get-the-corresponding-key-by-value.md":"MTDN91oy","collections_examples_format-github-events-score.md":"wfxYnsHX","collections_containsoneitem.md":"5VKQwaiG","collections_containsstrict.md":"_Q_AVUVc","collections_concat.md":"FU6M_Wjq","collections_sliding.md":"Rvg-4Lsd","collections_sole.md":"AMzUH7W7","collections_unless.md":"wt9qFqww","collections_wherein.md":"szKiQWo_","collections_flatten.md":"ogNL5TLn","collections_value.md":"F9GFBYsQ","collections_first.md":"zfZ7b16t","collections_uniquestrict.md":"QMR-tFNT","collections_except.md":"tgvKvobw","collections_takewhile.md":"Im8IT3ju","collections_tap.md":"SzGGWag7","collections_times.md":"qZhNCX8y","collections_toarray.md":"KXdkyKm8","collections_skipwhile.md":"uO3V_-ca","collections_diffkeysusing.md":"ixQGNKxS","collections_tojson.md":"89q0oi_g","collections_diffusing.md":"07Bpyu_U","collections_transform.md":"hwrsMzt0","collections_undot.md":"_rwyJHGY","collections_firstorfail.md":"fK1q00TB","collections_firstwhere.md":"KoMr1nHq","collections_unwrap.md":"Ny7VKXrn","readme.md":"jFA-2Pyx","collections_flip.md":"a2t84cAk","collections_collect.md":"ZUu63D3B","others_using-custom-exceptions-to-write-better-and-clearer-code.md":"x3YUnaaX","collections_skipuntil.md":"XNjlAzE9","collections_diffassocusing.md":"_mmpmAAe","collections_takeuntil.md":"ogQGRrkk","collections_whereinstrict.md":"OOLbqZCv","collections_whereinstanceof.md":"9I9I93zW","collections_values.md":"pVilbYJM","collections_duplicates.md":"vi00perh","collections_shift.md":"zV1VR6PR","collections_duplicatesstrict.md":"MoDb8M0f","collections_countby.md":"O1bayoZp","collections_dump.md":"OSgWHBEt","collections_random.md":"teXBoYU2","collections_unique.md":"qKQVg2uz","collections_splice.md":"f1DAzyU8","collections_when.md":"zxuogAYL","partials_validation.md":"xS4DbwrE","collections_last.md":"C0OkYuK5","collections_mapspread.md":"_TMsYpD8","collections_nth.md":"uT0JQZkH","collections_only.md":"4ugtRH2Q","others_macros.md":"x0jgMPke","packages_readme.md":"MxtBZ0lg","packages_index.md":"eym3JoAX","packages_pail.md":"9jiRHL8A","packages_pint.md":"hZtbp8hP","partials_routing.md":"BubcW3wU","packages_sushi.md":"VR1hkZvT","partials_readme.md":"WCpvt4sp","partials_migrations.md":"Tz41kgD7","collections_each.md":"yeSSzTuz","collections_eachspread.md":"RH33nv7-","collections_forpage.md":"wY-WeFTU","partials_urls.md":"6H0fiA4b","partials_model-relations.md":"SifYo8MP","tips_db-models-and-eloquent.md":"QeyCv8Q5","collections_every.md":"fh_cOrNA","collections_examples_order-info-summary.md":"bN_UE0uA","tips_reuse-the-environment-variable-value.md":"aGGykNAC","collections_where.md":"4X6UWksm","collections_median.md":"3TitTEAl","collections_mode.md":"GZLOSVMN","model_relationships_01-has-one.md":"hXt881MO","collections_diff.md":"7bKs1UyM","collections_pluck.md":"_Oqyf9oy","collections_sortbydesc.md":"tcXklm6H","model_relationships_08-morph-many.md":"DFHcfVdD","collections_has.md":"DdYyC1nF","collections_implode.md":"9fl-VldK","model_relationships_09-one-of-many.md":"gFzGrQdC","collections_partition.md":"uQnihVDL","model_relationships_readme.md":"it2M_Xa7","model_relationships_10-morph-to-many.md":"8ro73kvH","others_readme.md":"DytdaoIS","others_artisan-command-to-generate-views-in-laravel.md":"Oq9zvD1V","others_helpers_numbers.md":"GhLWTwOb","others_helpers_sleep.md":"2F2SFU7R","model_relationships_04-has-one-through.md":"eWEi4PPd","collections_sortdesc.md":"Erj0XKvL","collections_isempty.md":"7TDAf5nj","model_some-tips-for-optimize-database-queries.md":"4TUH-dBr","collections_union.md":"vG2lc9RD","collections_intersectbykeys.md":"_d2WRlan","collections_zip.md":"LPOgnnZd","collections_index.md":"sUcfmufH","collections_mergerecursive.md":"-esLkRjU","collections_push.md":"wcwtEV45","collections_pipe.md":"yHU_ovFR","collections_pipeinto.md":"h-g1H2Ns","collections_reverse.md":"cOi5WKA0","collections_keys.md":"ywDfOg7K","others_unit-test-laravel-api-pest-framework.md":"aH4wKJiA","collections_get.md":"8UpplnQv","collections_pop.md":"760_QhYk","collections_hasany.md":"1hDQgXnH","others_laravel-create-custom-facade-test-demo.md":"sDDcbHdA","collections_pull.md":"W5NHsPjl","collections_take.md":"nJEAyL77","collections_put.md":"SXXB5EYA","collections_prepend.md":"9C0SW6Fx","collections_reduce.md":"Bes_s56P","collections_examples_using-sum-method.md":"M_cEgkDV","collections_reject.md":"wLQNKa2x","collections_reducespread.md":"BKZXHiGj","collections_replace.md":"YPV3mwJx","collections_search.md":"aXd0qhA3","collections_shuffle.md":"liOyRrVJ","collections_replacerecursive.md":"NoHMI8w6","collections_skip.md":"WDrXVYsx","collections_examples_format-calculate-the-data-of-the-two-arrays.md":"j2cfwLel","collections_examples_using-reduce-create-lookup-array.md":"wR_t-2yG","collections_sortby.md":"_C6Pg8yM","collections_doesntcontain.md":"g3JVyEde","collections_whenempty.md":"HNh0YtjA","tips_readme.md":"-SavssMs","collections_examples_map-format.md":"k3ioX83T","packages_missing-livewire-assertions.md":"i9FJ3sLY","collections_sum.md":"F1AlplnV","tips_optimize-factory-database-batch-insert.md":"zhKOSvRZ","tips_process-large-csv-files-with-laravel-using-simple-excel.md":"JR1Jgsbk","packages_laravel-login-link.md":"JvVMGzDJ","collections_mapwithkeys.md":"3kbd9QOL","others_scroll-to-validation-error-in-laravel-using-alpinejs.md":"5jwmsCWy","others_laravel-import-custom-function-file.md":"cHxTiYgX","collections_mapinto.md":"vOv_ty53","collections_map.md":"R2X_Y4cP","collections_maptodictionary.md":"y55GmNET","collections_maptogroups.md":"ug8ZtMuf","collections_sort.md":"6CedJqzf","collections_avg.md":"-eWpt_GK","model_relationships_03-has-one-of-many.md":"uO26_n_u","collections_wherebetween.md":"lcNjzWZ1","model_relationships_05-has-many-through.md":"u3LKnI7r","partials_model.md":"vO6Sq_p3","collections_filter.md":"QkenjHVL","collections_diffkeys.md":"7S9FH9HG","collections_max.md":"5oeUpxqN","collections_sortkeys.md":"LJmOPS89","model_laravel-model-caching.md":"jDLJfVAB","collections_sortkeysdesc.md":"gLHNeGK5","collections_sortkeysusing.md":"2XxYnqen","collections_intersect.md":"cQeiHU-d","collections_wherenotbetween.md":"mTRKB1MF","collections_isnotempty.md":"WXJI3Ij8","collections_split.md":"efghKdwO","collections_wherenotin.md":"RntBltNW","collections_splitin.md":"Io_idGYb","collections_wherenotinstrict.md":"Os80tytO","collections_wherenotnull.md":"0FLWqOjr","model_relationships_07-morph-one.md":"NgJfJAuK","collections_join.md":"e3P9x8ad","collections_groupby.md":"0fEUUlyw","collections_keyby.md":"UflaS2lP","collections_wherestrict.md":"UgW1PYGg","collections_wrap.md":"0SAfJ068","collections_merge.md":"pqM7SQKQ","collections_flatmap.md":"WEdEWCkZ","partials_views.md":"cI6Ea_JL","collections_lazy.md":"f769xhzj","collections_macro.md":"F3cKl_qV","collections_slice.md":"RN732IYp","index.md":"UGhlXLoi","partials_testing.md":"e6oc5ff9","collections_make.md":"VlelNJLf","collections_pipethrough.md":"RFDoSyZu","model_laravel-model-observers.md":"ynZiZIq3","model_laravel-model-events.md":"xibZ0Aka","collections_wherenull.md":"q4-264ZA","model_relationships_02-has-many.md":"pF4KEa4z","collections_forget.md":"ZimG_JuT","model_index.md":"lhzR5xQN","collections_pad.md":"zVknAF0T","collections_min.md":"MqtTIb4S","collections_whennotempty.md":"SOQeFKg3","model_relationships_06-belongs-to-many.md":"tY0T-jwC"} +{"collections_diff.md":"7bKs1UyM","collections_duplicates.md":"vi00perh","model_relationships_09-one-of-many.md":"gFzGrQdC","collections_crossjoin.md":"-R0sMNmR","collections_eachspread.md":"RH33nv7-","collections_diffkeys.md":"7S9FH9HG","collections_containsstrict.md":"_Q_AVUVc","collections_containsoneitem.md":"5VKQwaiG","collections_zip.md":"LPOgnnZd","collections_has.md":"DdYyC1nF","collections_skipwhile.md":"uO3V_-ca","collections_examples_readme.md":"eCrhk73W","collections_get.md":"8QQmXJQ1","model_relationships_readme.md":"it2M_Xa7","others_readme.md":"DytdaoIS","others_artisan-command-to-generate-views-in-laravel.md":"Oq9zvD1V","others_helpers_numbers.md":"GhLWTwOb","others_helpers_sleep.md":"2F2SFU7R","others_laravel-import-custom-function-file.md":"cHxTiYgX","others_laravel-create-custom-facade-test-demo.md":"sDDcbHdA","collections_all.md":"oJwh_lKh","others_macros.md":"gakYAePd","packages_pail.md":"9jiRHL8A","packages_pint.md":"hZtbp8hP","model_relationships_08-morph-many.md":"DFHcfVdD","collections_count.md":"iQwti93y","collections_collapse.md":"oxuG8yyE","model_relationships_06-belongs-to-many.md":"tY0T-jwC","others_scroll-to-validation-error-in-laravel-using-alpinejs.md":"5jwmsCWy","model_laravel-model-caching.md":"jDLJfVAB","collections_examples_format-calculate-the-data-of-the-two-arrays.md":"j2cfwLel","collections_median.md":"3TitTEAl","collections_random.md":"teXBoYU2","collections_avg.md":"xLdaFj0z","collections_last.md":"C0OkYuK5","tips_readme.md":"-SavssMs","collections_examples_order-info-summary.md":"XqY9j1FS","index.md":"UGhlXLoi","collections_min.md":"MqtTIb4S","collections_merge.md":"pqM7SQKQ","partials_views.md":"Xvm8Qxt4","collections_mode.md":"GZLOSVMN","collections_countby.md":"l-Ea66bq","collections_map.md":"R2X_Y4cP","collections_mapinto.md":"vOv_ty53","collections_duplicatesstrict.md":"MoDb8M0f","collections_maptodictionary.md":"y55GmNET","collections_each.md":"yeSSzTuz","packages_sushi.md":"VR1hkZvT","collections_first.md":"S0hVTg0e","collections_pull.md":"W5NHsPjl","collections_firstorfail.md":"fK1q00TB","collections_firstwhere.md":"xLPb4fOu","collections_reducespread.md":"BKZXHiGj","packages_laravel-login-link.md":"Olxf7G32","collections_flatmap.md":"WEdEWCkZ","packages_missing-livewire-assertions.md":"i9FJ3sLY","collections_put.md":"SXXB5EYA","collections_push.md":"wcwtEV45","model_relationships_02-has-many.md":"pF4KEa4z","collections_flatten.md":"ogNL5TLn","collections_groupby.md":"0fEUUlyw","collections_chunkwhile.md":"Eld99fPB","collections_keys.md":"ywDfOg7K","collections_collect.md":"ZUu63D3B","model_relationships_04-has-one-through.md":"eWEi4PPd","collections_make.md":"VlelNJLf","collections_pop.md":"760_QhYk","partials_testing.md":"fbu4V60w","collections_intersect.md":"cQeiHU-d","collections_intersectbykeys.md":"_d2WRlan","collections_isnotempty.md":"WXJI3Ij8","collections_isempty.md":"7TDAf5nj","collections_filter.md":"QkenjHVL","collections_join.md":"e3P9x8ad","collections_pad.md":"zVknAF0T","collections_partition.md":"uQnihVDL","collections_index.md":"sUcfmufH","collections_pipeinto.md":"h-g1H2Ns","collections_pipethrough.md":"RFDoSyZu","collections_pipe.md":"yHU_ovFR","packages_index.md":"eym3JoAX","collections_pluck.md":"_Oqyf9oy","collections_flip.md":"a2t84cAk","collections_prepend.md":"9C0SW6Fx","tips_optimize-factory-database-batch-insert.md":"f82qCgz_","collections_examples_get-the-corresponding-key-by-value.md":"MTDN91oy","model_laravel-model-observers.md":"ynZiZIq3","collections_reject.md":"wLQNKa2x","collections_replace.md":"YPV3mwJx","collections_replacerecursive.md":"NoHMI8w6","collections_reverse.md":"cOi5WKA0","collections_search.md":"aXd0qhA3","collections_shift.md":"zV1VR6PR","collections_shuffle.md":"liOyRrVJ","collections_skip.md":"WDrXVYsx","collections_skipuntil.md":"XNjlAzE9","collections_slice.md":"RN732IYp","collections_sort.md":"6CedJqzf","collections_sole.md":"AMzUH7W7","collections_sortbydesc.md":"tcXklm6H","collections_sortdesc.md":"Erj0XKvL","collections_forpage.md":"wY-WeFTU","collections_sortkeys.md":"LJmOPS89","collections_sortkeysdesc.md":"gLHNeGK5","collections_sortkeysusing.md":"2XxYnqen","collections_sortby.md":"_C6Pg8yM","tips_db-models-and-eloquent.md":"ZlfaD_0T","collections_split.md":"efghKdwO","collections_splitin.md":"Io_idGYb","collections_sum.md":"F1AlplnV","collections_take.md":"nJEAyL77","collections_takeuntil.md":"ogQGRrkk","tips_process-large-csv-files-with-laravel-using-simple-excel.md":"JR1Jgsbk","tips_reuse-the-environment-variable-value.md":"9X_QhAK_","collections_examples_format-github-events-score.md":"hyfCyv4u","collections_combine.md":"2vPAOnff","collections_dd.md":"_oeIlJJ4","collections_diffkeysusing.md":"ixQGNKxS","collections_diffusing.md":"07Bpyu_U","collections_doesntcontain.md":"g3JVyEde","collections_dump.md":"OSgWHBEt","packages_backup.md":"tXZnViYm","model_relationships_01-has-one.md":"hXt881MO","collections_forget.md":"ZimG_JuT","collections_implode.md":"9fl-VldK","partials_migrations.md":"E0t3c2Hd","model_some-tips-for-optimize-database-queries.md":"4TUH-dBr","collections_hasany.md":"1hDQgXnH","others_unit-test-laravel-api-pest-framework.md":"aH4wKJiA","collections_examples_using-sum-method.md":"M_cEgkDV","collections_concat.md":"FU6M_Wjq","partials_validation.md":"TinoEwuN","partials_readme.md":"WCpvt4sp","others_using-custom-exceptions-to-write-better-and-clearer-code.md":"csYPuapg","collections_splice.md":"f1DAzyU8","model_relationships_07-morph-one.md":"NgJfJAuK","collections_sliding.md":"Rvg-4Lsd","collections_transform.md":"hwrsMzt0","collections_undot.md":"_rwyJHGY","readme.md":"apB3GTSz","model_laravel-model-events.md":"xibZ0Aka","collections_union.md":"vG2lc9RD","collections_unique.md":"qKQVg2uz","collections_mapwithkeys.md":"3kbd9QOL","collections_uniquestrict.md":"QMR-tFNT","collections_unless.md":"wt9qFqww","collections_mapspread.md":"_TMsYpD8","collections_maptogroups.md":"ug8ZtMuf","partials_urls.md":"6H0fiA4b","collections_except.md":"tgvKvobw","collections_unwrap.md":"Ny7VKXrn","collections_tojson.md":"89q0oi_g","collections_takewhile.md":"Im8IT3ju","collections_tap.md":"SzGGWag7","collections_times.md":"qZhNCX8y","collections_toarray.md":"KXdkyKm8","collections_values.md":"pVilbYJM","collections_diffassoc.md":"u_qdxAr0","collections_when.md":"zxuogAYL","collections_whennotempty.md":"SOQeFKg3","collections_whenempty.md":"HNh0YtjA","collections_where.md":"4X6UWksm","collections_wherebetween.md":"lcNjzWZ1","collections_wherein.md":"szKiQWo_","collections_whereinstanceof.md":"9I9I93zW","collections_whereinstrict.md":"OOLbqZCv","collections_wherenotbetween.md":"mTRKB1MF","collections_wherenull.md":"q4-264ZA","collections_wherestrict.md":"UgW1PYGg","collections_wrap.md":"0SAfJ068","collections_wherenotnull.md":"0FLWqOjr","collections_wherenotinstrict.md":"Os80tytO","collections_wherenotin.md":"RntBltNW","collections_examples_using-reduce-create-lookup-array.md":"dvs71PEo","model_relationships_10-morph-to-many.md":"8ro73kvH","collections_every.md":"fh_cOrNA","collections_examples_map-format.md":"k3ioX83T","collections_diffassocusing.md":"_mmpmAAe","model_index.md":"lhzR5xQN","collections_lazy.md":"f769xhzj","collections_nth.md":"uT0JQZkH","packages_readme.md":"XJEffmIi","collections_contains.md":"iYcKzst-","collections_max.md":"5oeUpxqN","model_relationships_05-has-many-through.md":"u3LKnI7r","collections_only.md":"4ugtRH2Q","collections_keyby.md":"UflaS2lP","collections_macro.md":"F3cKl_qV","collections_value.md":"F9GFBYsQ","partials_model-relations.md":"SifYo8MP","collections_chunk.md":"cOnAXM54","collections_mergerecursive.md":"-esLkRjU","collections_reduce.md":"Bes_s56P","collections_examples_markdown-format.md":"qABRGspv","partials_model.md":"dpslP7zF","partials_routing.md":"BubcW3wU","model_relationships_03-has-one-of-many.md":"uO26_n_u"} diff --git a/index.html b/index.html index 8170875b4..3b4e4cf3a 100644 --- a/index.html +++ b/index.html @@ -19,7 +19,7 @@
Skip to content

Laravel 学习记录

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

- + \ No newline at end of file diff --git a/model/index.html b/model/index.html index 3ce1c5f2d..139f7878e 100644 --- a/model/index.html +++ b/model/index.html @@ -19,7 +19,7 @@
- + \ No newline at end of file diff --git a/model/laravel-model-caching.html b/model/laravel-model-caching.html index 975b09d14..2358427bc 100644 --- a/model/laravel-model-caching.html +++ b/model/laravel-model-caching.html @@ -113,7 +113,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 859ba4d4c..cbd55d091 100644 --- a/model/laravel-model-events.html +++ b/model/laravel-model-events.html @@ -142,7 +142,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 9e225a496..e5217c0cc 100644 --- a/model/laravel-model-observers.html +++ b/model/laravel-model-observers.html @@ -151,7 +151,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 6cec949f4..8cf23b60f 100644 --- a/model/relationships/01-has-one.html +++ b/model/relationships/01-has-one.html @@ -280,7 +280,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 9a5b5af09..8974999f6 100644 --- a/model/relationships/02-has-many.html +++ b/model/relationships/02-has-many.html @@ -309,7 +309,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 d5fd27a40..16bfdca4d 100644 --- a/model/relationships/03-has-one-of-many.html +++ b/model/relationships/03-has-one-of-many.html @@ -319,7 +319,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 2a12b1910..bb77585c3 100644 --- a/model/relationships/04-has-one-through.html +++ b/model/relationships/04-has-one-through.html @@ -281,7 +281,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 d128b9f83..0236d376f 100644 --- a/model/relationships/05-has-many-through.html +++ b/model/relationships/05-has-many-through.html @@ -247,7 +247,7 @@ $user = $post->user->toArray(); // 获取文字所属用户
文章列表关联用户信息
$post = \App\Post::with('user')->get()->toArray();

关联删除

通过用户关联删除文章信息

$user = \App\User::find(1);
 $user->posts()->delete(); // 删除 posts 表中相关记录

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

$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 7fc02ed64..55f7399a0 100644 --- a/model/relationships/06-belongs-to-many.html +++ b/model/relationships/06-belongs-to-many.html @@ -355,7 +355,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 53060385b..01441689f 100644 --- a/model/relationships/07-morph-one.html +++ b/model/relationships/07-morph-one.html @@ -83,7 +83,7 @@ // 或者使用链式调用 \App\User::first()->image()->save(['url' => 'new url']);

删除关联数据

$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 b0c37215c..7830227a4 100644 --- a/model/relationships/08-morph-many.html +++ b/model/relationships/08-morph-many.html @@ -226,7 +226,7 @@ $commentable = \App\Comment::find(1)->commentable()->with('user')->first();

删除数据

删除一篇文章下的所有评论

$post = \App\Post::find(1);
 $post->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 a1d925942..b1184c301 100644 --- a/model/relationships/09-one-of-many.html +++ b/model/relationships/09-one-of-many.html @@ -19,7 +19,7 @@
- + \ 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 c50fb9f81..9c4a6ffac 100644 --- a/model/relationships/10-morph-to-many.html +++ b/model/relationships/10-morph-to-many.html @@ -153,7 +153,7 @@ $post->tags()->attach($tag->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 7c5b9a510..88e2e4d94 100644 --- a/model/relationships/README.html +++ b/model/relationships/README.html @@ -19,7 +19,7 @@
- + \ 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 78ea5961f..242e663b3 100644 --- a/model/some-tips-for-optimize-database-queries.html +++ b/model/some-tips-for-optimize-database-queries.html @@ -192,7 +192,7 @@ // or $posts = Post::orderBy('created_at', 'desc')->get();

上面的方法将产生以下sql查询。

php
select * from posts order by created_at desc

该查询基本上是基于 created_at 列以降序对行进行排序。

由于 created_at 列是基于字符串的列,因此以这种方式对结果进行排序通常较慢。

如果您的数据库表具有自动递增的主键ID,则在大多数情况下,最新行将始终具有最高ID。 由于 id 字段既是整数字段又是主键,因此基于此键对结果进行排序要快得多。因此,检索最新行的更好方法如下。

php
$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 02ea4debd..05a90a819 100644 --- a/others/README.html +++ b/others/README.html @@ -19,7 +19,7 @@
- + \ No newline at end of file diff --git a/others/artisan-command-to-generate-views-in-laravel.html b/others/artisan-command-to-generate-views-in-laravel.html index 7b512087c..228cea091 100644 --- a/others/artisan-command-to-generate-views-in-laravel.html +++ b/others/artisan-command-to-generate-views-in-laravel.html @@ -21,7 +21,7 @@
Skip to content

生成视图的 Artisan 命令

Laravel 默认自带各种命令,可以为应用程序生成样板代码。

例如,可以使用 Artisan 命令生成控制器、模型、数据库迁移文件等。

但是,截止到 Laravel 10.x 之前还没有生成视图的命令。

随着 Laravel 10.x 的发布,这种情况发生了变化。

在这个版本中,现在可以使用 make:view 命令生成视图。

生成视图

bash
php artisan make:view about-us

执行完上面的命令后,会在项目中生成一个新的视图文件 resources/views/about-us.blade.php

如果需要生成嵌套目录的视图文件,可以使用 . 或者 / 分割它们。比如生成一个 resources/views/posts/index.blade.php 的视图文件,可以使用下面的命令:

bash
php artisan make:view posts.index
 # Also can use below
 php artisan make:view posts/index

选项

如果需要在生成视图的同时生成一个测试文件,可以传入 --test 选项。

  • --test

    bash
    php artisan make:view about-us --test

    额外生成 tests/Feature/View/AboutUsTest.php 的 PHPUnit 测试文件

  • --pest

    bash
    php artisan make:view about-us --pest

    额外生成 tests/Feature/View/AboutUsTest.php 的 Pest 测试文件

- + \ No newline at end of file diff --git a/others/helpers/numbers.html b/others/helpers/numbers.html index 0d541b30d..92f9b2ff2 100644 --- a/others/helpers/numbers.html +++ b/others/helpers/numbers.html @@ -70,7 +70,7 @@ Number::forHumans(1234000, precision: 2); // 1.23 million Number::forHumans(1234000, maxPrecision: 2); // 1.23 million - + \ No newline at end of file diff --git a/others/helpers/sleep.html b/others/helpers/sleep.html index 833ef87dd..20719c34f 100644 --- a/others/helpers/sleep.html +++ b/others/helpers/sleep.html @@ -62,7 +62,7 @@ // ... });

当伪造 Sleep 类时,实际的执行暂停被绕过,从而导致测试速度大大加快。

- + \ 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 07ab216d3..3f06d6e9e 100644 --- a/others/laravel-create-custom-facade-test-demo.html +++ b/others/laravel-create-custom-facade-test-demo.html @@ -107,7 +107,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 74e1abbaf..7886962c7 100644 --- a/others/laravel-import-custom-function-file.html +++ b/others/laravel-import-custom-function-file.html @@ -46,7 +46,7 @@ ] } }

执行自动加载

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

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

- + \ No newline at end of file diff --git a/others/macros.html b/others/macros.html index 1977bca1f..2f7d1ca0b 100644 --- a/others/macros.html +++ b/others/macros.html @@ -12,7 +12,7 @@ - + @@ -108,7 +108,7 @@ { Str::mixin(new StrMixin); //[!code ++] } -}

现在,如果在 Str 类上测试 isLength()appendTo() 方法,将得到相同的结果。

一些示例

Model

php
<?php
+}

现在,如果在 Str 类上测试 isLength()appendTo() 方法,将得到相同的结果。

一些示例

Model

php
<?php
 
 use Illuminate\Support\ServiceProvider;
 use Illuminate\Database\Eloquent\Builder;
@@ -203,7 +203,7 @@
 });

Form

php
Form::micro('customInput', function($name, $value) {
     return "<input type='text' name='{$name}' value='{$value}' />";
 });
- + \ No newline at end of file diff --git a/others/scroll-to-validation-error-in-laravel-using-alpinejs.html b/others/scroll-to-validation-error-in-laravel-using-alpinejs.html index 3247ada37..06049a6ab 100644 --- a/others/scroll-to-validation-error-in-laravel-using-alpinejs.html +++ b/others/scroll-to-validation-error-in-laravel-using-alpinejs.html @@ -36,7 +36,7 @@ {{ $message }} </p> @enderror

如果错误消息容器在页面上可见,x-init 指令中的代码会将页面滚动到最近的表单元素。

这样,用户将能够看到所有验证错误,即使它们不在窗口中。

- + \ No newline at end of file diff --git a/others/unit-test-laravel-api-pest-framework.html b/others/unit-test-laravel-api-pest-framework.html index ea5905264..7d967f74b 100644 --- a/others/unit-test-laravel-api-pest-framework.html +++ b/others/unit-test-laravel-api-pest-framework.html @@ -251,7 +251,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

Run pest test passed

结论

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

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

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

原文链接

- + \ 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 6dd91d753..f727bb30d 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 @@ -12,7 +12,7 @@ - + @@ -50,7 +50,7 @@ 'message' => 'Ticket purchased successfully.', ]); } -}

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

php
<?php
+}

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

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

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

- + \ No newline at end of file diff --git a/packages/README.html b/packages/README.html index 96b0f53af..e4a340f87 100644 --- a/packages/README.html +++ b/packages/README.html @@ -12,14 +12,14 @@ - + -
- +
+ \ No newline at end of file diff --git a/packages/backup.html b/packages/backup.html new file mode 100644 index 000000000..3cc3c9afd --- /dev/null +++ b/packages/backup.html @@ -0,0 +1,124 @@ + + + + + + spatie/laravel-backup | Laravel 学习记录 + + + + + + + + + + + + + + +
Skip to content

spatie/laravel-backup

Laravel Backup 允许创建应用程序的备份,包括数据库、源代码或用户上传的文件。

备份可以存储在配置的自定义文件系统上,比如 S3、七牛云或者 ftp 等。

当备份出现问题时,该扩展包还可以通过邮件等发送通知。

安装

通过 Composer 安装该软件包:

bash
composer require spatie/laravel-backup

配置

使用下面的命令发布配置文件 config/backup.php

bash
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

建议修改配置文件内容:

php
<?php
+
+ 'backup' => [
+        // ...
+        'name' => env('APP_NAME', 'laravel-backup'), 
+        'name' => env('BACKUP_NAME', 'laravel-backup'), 
+        'destination' => [
+            // ...
+            'disks' => [ 
+                'local', 
+            ], 
+            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
+        ],
+    ],
+    'monitor_backups' => [
+        [
+            'name' => env('APP_NAME', 'laravel-backup'), 
+            'disks' => ['local'], 
+            'name' => env('BACKUP_NAME', 'laravel-backup'), 
+            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
+            'health_checks' => [
+                \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays::class => 1,
+                \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes::class => 5000,
+            ],
+        ],
+    ],

然后可以在 .env 配置文件中添加两个自定义环境变量 BACKUP_NAME 备份名称和 BACKUP_DISKS 需要备份到的磁盘。

使用

常用命令

  • 备份所有文件

    bash
    php artisan backup:run
  • 仅备份数据库

    bash
    php artisan backup:run --only-db
  • 列出所有备份文件

    bash
    php artisan backup:list
  • 清空旧备份文件

    bash
    php artisan backup:clean

通知

默认情况下,备份任务完成后会通过发送通知到 your@example.com 用户。

可以通过 config/backup.php 文件中的 config('backup.notifications.mail') 配置项来修改通知配置。

或者通过 config/backup.php 文件中的 config('backup.notifications.notifications') 配置项移除 mail 来关闭邮件通知。

备份到七牛云

默认数据的备份文件放在本地,可以配置一些其他存储方式,比如七牛云存储。

  1. 安装驱动依赖

    bash
    composer require overtrue/laravel-filesystem-qiniu
  2. 配置 config/filesystems.php 文件

    php
    <?php
    +
    +return [
    +    // ...
    +    'disks' => [
    +        // ...
    +        'qiniu-backup' => [ 
    +            'driver' => 'qiniu', 
    +            'access_key' => env('BACKUP_QINIU_ACCESS_KEY', ''), 
    +            'secret_key' => env('BACKUP_QINIU_SECRET_KEY', ''), 
    +            'bucket' => env('BACKUP_QINIU_BUCKET', ''), 
    +            'domain' => env('BACKUP_QINIU_DOMAIN', ''),  
    +        ], 
    +    ]
    +    // ...
    +];
  3. 修改 config/backup.php 文件中关于 disks 的配置

    php
    <?php
    +return [
    +    'backup' => [
    +        // ...
    +        'destination' => [
    +            // ...
    +            'disks' => [ 
    +                'local', 
    +            ], 
    +            'disks' => explode(',', env('BACKUP_DISKS', 'local')), [ 
    +        ],
    +        // ...
    +    ],
    +    'monitor_backups' => [
    +        [
    +            // ...
    +            'disks' => ['local'],
    +            'disks' => explode(',', env('BACKUP_DISKS', 'local')), 
    +            // ...
    +        ],
    +        // ...
    +   ],
    +];
  4. 本地 .env 文件新增环境变量

    dotenv
    # Backup
    +BACKUP_QINIU_ACCESS_KEY=
    +BACKUP_QINIU_SECRET_KEY=
    +BACKUP_QINIU_BUCKET=my-backup
    +BACKUP_QINIU_DOMAIN=https://backup.domain.com
    +# support local、qiniu-backup
    +BACKUP_DISKS=local,qiniu-backup

备份定时任务

php
<?php
+
+namespace App\Console;
+
+use Illuminate\Console\Scheduling\Schedule;
+use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
+
+class Kernel extends ConsoleKernel
+{
+    protected function schedule(Schedule $schedule): void
+    {
+        $schedule->command('backup:run --only-db')->daily()->at('02:05'); // 凌晨2点5分备份数据库
+        $schedule->command('backup:clean')->daily()->at('02:05'); // 凌晨2点5分清理旧的备份
+        $schedule->command('backup:monitor')->daily()->at('10:05'); // 早上10点05分检查数据库备份
+    }
+    // ...
+}

mysql-dump 命令路径

  1. config/database.php 中添加自定义配置
    php
    <?php
    +
    +use Illuminate\Support\Str;
    +
    +return [
    +    'connections' => [
    +
    +        'mysql' => [
    +            // ...
    +            'dump' => [ 
    +                'dump_binary_path' => env('DUMP_BINARY_PATH', '/usr/local/mysql/bin'), 
    +            ], 
    +        ],
    +    ],
    +];
  2. 在本地环境文件 .env 中添加
dotenv
# For Apple M1
+DUMP_BINARY_PATH=/opt/homebrew/bin
+ + + + \ No newline at end of file diff --git a/packages/index.html b/packages/index.html index 6a60d3d1f..e0c035180 100644 --- a/packages/index.html +++ b/packages/index.html @@ -18,8 +18,8 @@ -
- +
+ \ No newline at end of file diff --git a/packages/laravel-login-link.html b/packages/laravel-login-link.html index d0c68bb54..dd5cc6c72 100644 --- a/packages/laravel-login-link.html +++ b/packages/laravel-login-link.html @@ -12,13 +12,13 @@ - + -
Skip to content
- + \ No newline at end of file diff --git a/partials/routing.html b/partials/routing.html index 79c3f7a62..6d9e639b6 100644 --- a/partials/routing.html +++ b/partials/routing.html @@ -247,7 +247,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 42915e48e..11eb1fabf 100644 --- a/partials/testing.html +++ b/partials/testing.html @@ -12,7 +12,7 @@ - + @@ -32,7 +32,7 @@ $firstProduct->title, $secondProduct->title, ]); -});

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

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

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

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

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

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

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

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

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

php
it('returns correct view', function() {
     // Act & Assert
     $this->get('/')
         ->assertOk()
@@ -96,7 +96,7 @@
                 'description' => $anotherProduct->description,
             ],
         ]);
-});
  • assertJsonCount() 第二个参数支持传入指定键,比如 ->assertJsonCount(10, 'data')
  • assertJsonStructure() 支持使用 * 对数组进行匹配,比如:assertJsonStructure(['data' => ['*' => ['title', 'description']]])

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

数据库 Database

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

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

php
// 该示例确保 post 请求成功并将数据正确的存储在数据库中。
+});
  • assertJsonCount() 第二个参数支持传入指定键,比如 ->assertJsonCount(10, 'data')
  • assertJsonStructure() 支持使用 * 对数组进行匹配,比如:assertJsonStructure(['data' => ['*' => ['title', 'description']]])

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

数据库 Database

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

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

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

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

资源 Resources

php
// tests/Feature/Http/Resources/UsersResourceTest.php
+});

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

资源 Resources

php
// tests/Feature/Http/Resources/UsersResourceTest.php
 <?php
 
 use App\Http\Resources\UsersResource;
@@ -166,7 +166,7 @@
             'created_at' => $this->resource->created_at->toDateTimeString(),
         ];
     }
-}

请求 Requests

有时候需要单独测试自定义请求规则,可以直接对自定义请求类进行测试。

php
<?php
+}

请求 Requests

有时候需要单独测试自定义请求规则,可以直接对自定义请求类进行测试。

php
<?php
 
 // tests\Feature\Http\Requests\SiteStoreRequestTest
 
@@ -239,7 +239,7 @@
             $fail('URL 必须包含协议,例如:http:// 或 https://');
         }
     }
-}

验证 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', [
@@ -260,7 +260,7 @@
 })->with([
     'title required' => [['description' => 'text'], ['title' => 'required']],
     'description required' => [['title' => 'Title'], ['description' => 'required']],
-]);

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

也可以在此基础上引入 RequestsFactories 请求工厂,更加规范的进行测试,详细内容可以查看这里

自定义规则

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

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

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

也可以在此基础上引入 RequestsFactories 请求工厂,更加规范的进行测试,详细内容可以查看这里

自定义规则

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

php
it('has valid phone number for chinesePhoneNumber rule',
     fn ($value) => expect(new ChinesePhoneNumberRule())->toPassWith($value)
 )->with([
     [13800138000],
@@ -284,7 +284,7 @@
             $fail(__('validation.invalid_chinese_phone_number'));
         }
     }
-}

或者通过使用 Mockery::spy模拟验证。

php
<?php
+}

或者通过使用 Mockery::spy模拟验证。

php
<?php
 
 use App\Rules\PhoneNumber;
 
@@ -355,7 +355,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();
@@ -367,7 +367,7 @@
 });
php
// 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'])
 
@@ -380,7 +380,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();
@@ -448,7 +448,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
@@ -486,7 +486,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();
@@ -515,7 +515,7 @@
         ->expectsQuestion('Please provide the user ID of the user you want to merge', $userToBeMerged->id)
         ->expectsOutput('Accounts merged successfully')
         ->assertSuccessful(); // 可以期待输出并确保命令成功,这意味着退出代码为 0。
-});

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

测试视图 Views

Laravel 10.x 支持使用命令创建视图。

php
<?php
+});

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

测试视图 Views

Laravel 10.x 支持使用命令创建视图。

php
<?php
 // tests/Feature/View/Posts/IndexTest.php
 
 use App\Models\Post;
@@ -536,7 +536,7 @@
             <li>{{ $post->name }}</li>
         @endforeach
     </ul>
-</div>

中间件 Middlewares

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

php
<?php
+</div>

中间件 Middlewares

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

php
<?php
 // tests/Unit/Http/Middleware/RedirectMiddlewareTest.php
 
 use App\Models\Redirect;
@@ -718,7 +718,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',
@@ -782,7 +782,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();
 
@@ -806,7 +806,7 @@
     }
 }

架构测试 Architecture

PEST 引入了一种称为架构测试的新型测试,这是一种测试应用程序架构并确保它遵循定义的代码规则,并且可以确保代码保持干净且可维护的好方法。

php
test('no forgotten debug statements')
     ->expect(['dd', 'dump', 'var_dump', 'ray'])
-    ->not->toBeUsed();

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

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

定时任务 Schedules

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

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

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

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

定时任务 Schedules

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

php
<?php
 // App\Console\Kernel
 
 // ...
@@ -833,7 +833,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 f29cd35f6..847c5b22c 100644 --- a/partials/urls.html +++ b/partials/urls.html @@ -46,7 +46,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 f0398fe45..1ca0a3b02 100644 --- a/partials/validation.html +++ b/partials/validation.html @@ -12,7 +12,7 @@ - + @@ -223,7 +223,7 @@ { 'prices.*.amount.required' => 'Please provide an amount for price #:position' } -}

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

排除验证值

当需要验证某个字段,但实际上并不需要它进行任何操作时,比如“接受条款和条件”,使用 exclude 规则。

这样,调用验证的方法 validated 就不会返回它。

php
class UserStoreRequest extends FormRequest
+}

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

排除验证值

当需要验证某个字段,但实际上并不需要它进行任何操作时,比如“接受条款和条件”,使用 exclude 规则。

这样,调用验证的方法 validated 就不会返回它。

php
class UserStoreRequest extends FormRequest
 {
     public function rules(): array
     {
@@ -248,7 +248,7 @@
 Validator::make(['color' => '#f00'], ['color' => 'hex_color'])->passes(); // true
 
 Validator::make(['color' => '#ggg'], ['color' => 'hex_color'])->passes(); // false
- + \ No newline at end of file diff --git a/partials/views.html b/partials/views.html index dd92718b8..8472383db 100644 --- a/partials/views.html +++ b/partials/views.html @@ -12,7 +12,7 @@ - + @@ -30,7 +30,7 @@ <p>This is user {{ $user->id }}</p> @endforeach

$loop 变量还包含各种其他有用的属性:

属性描述
$loop->index当前循环迭代的索引(从 0 开始)。
$loop->iteration当前循环迭代(从 1 开始)。
$loop->remaining循环中剩余的迭代。
$loop->count正在迭代的数组中的项目总数。
$loop->first是否是循环的第一次迭代。
$loop->last是否是循环的最后一次迭代。
$loop->even是否是循环中的偶数迭代。
$loop->odd是否是循环中的奇数迭代。
$loop->depth当前循环的嵌套级别。
$loop->parent在嵌套循环中时,父循环变量。

官方文档 查看更多。

判断模版是否存在

可以在实际加载之前检查视图文件是否存在。

php
if (view()->exists('custom.page')) {
  // Load the view
-}

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

php
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`
php
// 1. 路由定义
+}

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

php
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`
php
// 1. 路由定义
 Route::get('about', [\App\Https\Controllers\PagesController::class, 'about']);
 
 // 2. 控制器
@@ -40,7 +40,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
php
@auth
 // 用户已验证身份
@@ -74,9 +74,9 @@
 
 @unlessenabled('regular-registration')
 // 该应用程序不接受常规注册
-@endenabled

IncludeIf, IncludeWhen, IncludeFirst 指令

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

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

IncludeIf, IncludeWhen, IncludeFirst 指令

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

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

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

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

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

php
@include("components.post", ["title" => $post->title])
html
<!--使用 Blade-X-->
 <x-post link="{{ $post->title }}"/>
 
 <!--使用 Blade-X 绑定变量-->
@@ -108,7 +108,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>
@@ -148,7 +148,7 @@
 }
php
// 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 }}
@@ -164,7 +164,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>
@@ -190,9 +190,9 @@
 
 @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))/>
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' }}/>

@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>
php
<select name="country">
@@ -212,7 +212,7 @@
  
 info("Executing deploy script...");
 $process = $ssh->execute(explode("\n", $script));
- + \ No newline at end of file diff --git a/tips/README.html b/tips/README.html index 6c03d6722..910f6fd5b 100644 --- a/tips/README.html +++ b/tips/README.html @@ -19,7 +19,7 @@ - + \ No newline at end of file diff --git a/tips/db-models-and-eloquent.html b/tips/db-models-and-eloquent.html index b80c4be80..8798890e4 100644 --- a/tips/db-models-and-eloquent.html +++ b/tips/db-models-and-eloquent.html @@ -12,7 +12,7 @@ - + @@ -47,7 +47,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);
 }
@@ -58,7 +58,7 @@
 }
php
public function scopePublished($query)
 {
     return $query->where('is_published', true);
-}

多个查询范围

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

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

多个查询范围

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

php
User::registeredWithinDays(30)->active()->get();
php
public function scopeActive($query) {
     return $query->where('active', 1);
 }
  
@@ -68,7 +68,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()
     {
@@ -95,7 +95,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');
@@ -135,7 +135,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'),
@@ -184,7 +184,7 @@
     }
 }

groupBy 按首字母分组

可以在 groupBy 接收自定义回调中按任何自定义条件对查询结果进行分组,以下是如何按公司名的首字母进行分组

php
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
 {
@@ -215,7 +215,7 @@
 User::find([1,2,3], ['first_name', 'email']);

whereKey 按主键查找

使用 whereKey() 方法查找多个记录,该方法负责确定哪个字段正是您的主键(id 是默认值,但可以在 Eloquent 模型中覆盖它)

php
User::whereKey([1, 2, 3])->get();

使用 UUID 代替自动递增

在模型中使用自动递增 ID。

迁移文件:

php
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
@@ -274,7 +274,7 @@
     }
 }

DB::statement() 查询方式

如果需要执行一个简单的 SQL 查询,但没有得到任何结果。

比如更改数据库中的某些内容,可以只执行 DB::statement()

php
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]
 );
php
Flight::where('departure', 'Oakland')
@@ -440,7 +440,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(...);
  
@@ -483,7 +483,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 e9c6589ab..692186be3 100644 --- a/tips/optimize-factory-database-batch-insert.html +++ b/tips/optimize-factory-database-batch-insert.html @@ -12,13 +12,13 @@ - + -
Skip to content

优化 Factory 数据库批量插入

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

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

优化 Factory 数据库批量插入

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

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

具体代码查看仓库地址github.com/curder/laravel-tips

执行速度对比

php
// Before
@@ -32,7 +32,7 @@
     Post::factory()->count(1000)->make()->toArray()
 );
 ray(microtime(true) - $start); // 0.15621304512024

- + \ No newline at end of file diff --git a/tips/process-large-csv-files-with-laravel-using-simple-excel.html b/tips/process-large-csv-files-with-laravel-using-simple-excel.html index 3f2c9512f..9c464ea86 100644 --- a/tips/process-large-csv-files-with-laravel-using-simple-excel.html +++ b/tips/process-large-csv-files-with-laravel-using-simple-excel.html @@ -140,7 +140,7 @@ ); } }
- + \ 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 82337bd21..cd3b02e63 100644 --- a/tips/reuse-the-environment-variable-value.html +++ b/tips/reuse-the-environment-variable-value.html @@ -12,16 +12,16 @@ - + -
Skip to content

重用环境变量值

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

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

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

重用环境变量值

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

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

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