书香隽秀 - Laravel 10
type: channel
link: https://www.huangshuxiu.com/laravel/
description: Laravel 10
items: Collections
items: Eloquent: Collections
items: Eloquent ORM
items: Illuminate Database
items: Database: Query Builder
items: VSCode快捷键
items: Carbon文档
items: Carbon常用方法
items: Laravel 8.x新增的AsArrayObject和AsCollection字段映射（casts）
items: Release Notes

Collections
type: item
date: 2023-05-25T09:00:00+08:00
description: CollectionsIntroductionThe Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.Creating CollectionsAs mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:$collection = collect([1, 2, 3]);The results of Eloquent queries are always returned as Collection instances.Extending CollectionsCollections are "macroable", which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class' macro method accepts a closure that will be executed when your macro is called. The macro closure may access the collection's other methods via $this, just as if it were a real method of the collection class. For example, the following code adds a toUpper method to the Collection class:use Illuminate\Support\Collection; use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND']Typically, you should declare collection macros in the boot method of a service provider.Macro ArgumentsIf necessary, you may define macros that accept additional arguments:use Illuminate\Support\Collection; use Illuminate\Support\Facades\…

Eloquent: Collections
type: item
date: 2023-05-24T22:55:27+08:00
description: Eloquent: CollectionsIntroductionAll Eloquent methods that return more than one model result will return instances of the Illuminate\Database\Eloquent\Collection class, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends Laravel's base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:use App\Models\User; $users = User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; }However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user:$names = User::all()->reject(function ($user) { return $user->active === false; })->map(function ($user) { return $user->name; });Eloquent Collection ConversionWhile most Eloquent collection methods return a new instance of an Eloquent collection, the collapse, flatten, flip, keys, pluck, and zip methods return a base collection instance. Likewise, if a map operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance.Available MethodsAll Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class.In addition, the Illuminate\Database\Eloquent\Collection class provides a superset of methods to aid with managing your model collections. Most methods return Illuminate\Database\Eloquent\Collection instances; however, some methods, like modelKeys, return an Illuminate\Support\Collection instance.containsdiffexceptfindfr…

Eloquent ORM
type: item
date: 2023-05-24T21:56:00+08:00
description: Eloquent: Getting StartedIntroductionLaravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.Before getting started, be sure to configure a database connection in your application's config/database.php configuration file. For more information on configuring your database, check out the database configuration documentation.Generating Model ClassesTo get started, let's create an Eloquent model. Models typically live in the app\Models directory and extend the Illuminate\Database\Eloquent\Model class. You may use the make:model Artisan command to generate a new model:php artisan make:model FlightIf you would like to generate a database migration when you generate the model, you may use the --migration or -m option:php artisan make:model Flight --migrationYou may generate various other types of classes when generating a model, such as factories, seeders, policies, controllers, and form requests. In addition, these options may be combined to create multiple classes at once:# Generate a model and a FlightFactory class... php artisan make:model Flight --factory php artisan make:model Flight -f # Generate a model and a FlightSeeder class... php artisan make:model Flight --seed php artisan make:model Flight -s # Generate a model and a FlightController class... php artisan make:model Flight --controller php artisan make:model Flight -c # Generate a model, FlightController resource class, and form request classes... php artisan make:model Flight --controller --resource --requests php artisan make:model Flight -crR # Generate a model and a FlightPolicy class... php artisan make:model Flight --policy # Generate a model and a migration, factory, seeder, and controller.…

Illuminate Database
type: item
date: 2023-05-20T09:53:00+08:00
description: ## [Illuminate Database](https://github.com/illuminate/database/tree/master) The Illuminate Database component is a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style ORM, and schema builder. It currently supports MySQL, Postgres, SQL Server, and SQLite. It also serves as the database layer of the Laravel PHP framework. ### Usage Instructions First, create a new "Capsule" manager instance. Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible.use Illuminate\Database\Capsule\Manager as Capsule;$capsule = new Capsule;$capsule->addConnection(['driver' => 'mysql','host' => 'localhost','database' => 'database','username' => 'root','password' => 'password','charset' => 'utf8','collation' => 'utf8_unicode_ci','prefix' => '',]);// Setup the Eloquent ORM... (optional)$capsule->bootEloquent();// Set the event dispatcher used by Eloquent models... (optional)$capsule->setEventDispatcher(...);// Set the cache manager instance used by connections... (optional)$capsule->setCacheManager(...);// Make this Capsule instance available globally via static methods... (optional)$capsule->setAsGlobal(); Once the Capsule instance has been registered. You may use it like so: **Using The Query Builder** $users = Capsule::table('users')->where('votes', '>' 100)->get(); Other core methods may be accessed directly from the Capsule in the same manner as from the DB facade: $results = Capsule::select('select * from users where id = ?', array(1)); **Using The Schema Builder** Capsule::schema()->create('users', function($table){$table->increments('id');$table->string('email')->unique();$table->timestamps();}); **Using The Eloquent ORM** class User extends Illuminate\Database\Eloquent\Model {}$users = User::where('votes', '>', 1)->get();

Database: Query Builder
type: item
date: 2023-05-19T14:36:00+08:00
description: IntroductionLaravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean or sanitize strings passed to the query builder as query bindings.PDO does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns.Running Database QueriesRetrieving All Rows From A TableYou may use the table method provided by the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally retrieve the results of the query using the get method:<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class UserController extends Controller { /** * Show a list of all of the application's users. * * @return \Illuminate\Http\Response */ public function index() { $users = DB::table('users')->get(); return view('user.index', ['users' => $users]); } }The get method returns an Illuminate\Support\Collection instance containing the results of the query where each result is an instance of the PHP stdClass object. You may access each column's value by accessing the column as a property of the object:use Illuminate\Support\Facades\DB; $users = DB::table('users')->get(); foreach ($users as $user) { echo $user->name; }Laravel collections provide a variety of extremely powerful methods for mapping and reducing data. For more information on Laravel collections, check out the collection documentation.Retrieving A Single Row / Column From A TableIf you just need to retrieve a single row from a database table, you …

VSCode快捷键
type: item
date: 2023-05-18T10:51:00+08:00
description: VSCode快捷键按Press功能FunctionCtrl+Shift+P,F1显示命令面板 Show Command PaletteCtrl + P快速打开 Quick OpenCtrl + Shift + N新窗口/实例 New window/instanceCtrl + Shift + W关闭窗口/实例 Close window/instance基础编辑Basic Editing按 Press功能 FunctionCtrl+X剪切行（空选定） Cut line (empty selection)Ctrl+C复制行（空选定）Copy line (empty selection)Alt+ ↑ / ↓向上/向下移动行 Move line up/downShift+Alt + ↓ / ↑向上/向下复制行 Copy line up/downCtrl+Shift+K删除行 Delete lineCtrl+Enter在下面插入行 Insert line belowCtrl+Shift+Enter在上面插入行 Insert line aboveCtrl+Shift+\跳到匹配的括号 Jump to matching bracketCtrl+] / [缩进/缩进行 Indent/outdent lineHome转到行首 Go to beginning of lineEnd转到行尾 Go to end of lineCtrl+Home转到文件开头 Go to beginning of fileCtrl+End转到文件末尾 Go to end of fileCtrl+↑ / ↓向上/向下滚动行 Scroll line up/downAlt+PgUp / PgDown向上/向下滚动页面 Scroll page up/downCtrl+Shift+[折叠（折叠）区域 Fold (collapse) regionCtrl+Shift+]展开（未折叠）区域 Unfold (uncollapse) regionCtrl+K Ctrl+[折叠（未折叠）所有子区域 Fold (collapse) all subregionsCtrl+K Ctrl+]展开（未折叠）所有子区域 Unfold (uncollapse) all subregionsCtrl+K Ctrl+0折叠（折叠）所有区域 Fold (collapse) all regionsCtrl+K Ctrl+J展开（未折叠）所有区域 Unfold (uncollapse) all regionsCtrl+K Ctrl+C添加行注释 Add line commentCtrl+K Ctrl+U删除行注释 Remove line commentCtrl+/切换行注释 Toggle line commentShift+Alt+A切换块注释 Toggle block commentAlt+Z切换换行 Toggle word wrap导航按 Press功能 FunctionCtrl + T显示所有符号 Show all SymbolsCtrl + G转到行... Go to Line...Ctrl + P转到文件... Go to File...Ctrl + Shift + O转到符号... Go to Symbol...Ctrl + Shift + M显示问题面板 Show Problems panelF8转到下一个错误或警告 Go to next error or warningShift + F8转到上一个错误或警告 Go to previous error or warningCtrl + Shift + Tab导航编辑器组历史记录 Navigate editor group historyAlt + ←/→返回/前进 Go back / forwardCtrl + M切换选项卡移动焦点 Toggle Tab moves focus搜索和替换 Search and replace按 Press功能 FunctionCtrl + F查找 FindCtrl + H替换 ReplaceF3 / Shift + F3查找下一个/上一个 Find next/previousAlt + Enter选择查找匹配的所有出现 Select all occurences of Find matchCtrl + D将选择添加到下一个查找匹配 Add selection to next Find matchCtrl + K Ctrl + D将最后一个选择移至下一个查找匹配项 Move last selection to next Find matchAlt + C / R / W切换区分大小写/正则表达式/整个词 Toggle…

Carbon文档
type: item
date: 2023-05-17T20:55:00+08:00
description: Introduction<?php namespace Carbon; class Carbon extends \DateTime { // code here }use Carbon\Carbon;We also provide CarbonImmutable class extending DateTimeImmutable. The same methods are available on both classes but when you use a modifier on a Carbon instance, it modifies and returns the same instance, when you use it on CarbonImmutable, it returns a new instances with the new value.<?php $mutable = Carbon::now(); $immutable = CarbonImmutable::now(); $modifiedMutable = $mutable->add(1, 'day'); $modifiedImmutable = CarbonImmutable::now()->add(1, 'day'); var_dump($modifiedMutable === $mutable); // bool(true) var_dump($mutable->isoFormat('dddd D')); // string(11) "Saturday 22" var_dump($modifiedMutable->isoFormat('dddd D')); // string(11) "Saturday 22" // So it means $mutable and $modifiedMutable are the same object // both set to now + 1 day. var_dump($modifiedImmutable === $immutable); // bool(false) var_dump($immutable->isoFormat('dddd D')); // string(9) "Friday 21" var_dump($modifiedImmutable->isoFormat('dddd D')); // string(11) "Saturday 22" // While $immutable is still set to now and cannot be changed and // $modifiedImmutable is a new instance created from $immutable // set to now + 1 day. $mutable = CarbonImmutable::now()->toMutable(); var_dump($mutable->isMutable()); // bool(true) var_dump($mutable->isImmutable()); // bool(false) $immutable = Carbon::now()->toImmutable(); var_dump($immutable->isMutable()); // bool(false) var_dump($immutable->isImmutable()); // bool(true)Carbon has all of the functions inherited from the base DateTime class. This approach allows you to access the base functionality such as modify, format or diff.<?php $dtToronto = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Toronto'); $dtVancouver = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Vancouver'); // Try to replace the 4th number (hours) or the last argument (timezone) with // Europe/Paris for example and see the actual result on the right hand. // It's alive! echo $dtVancouver->d…

Carbon常用方法
type: item
date: 2023-05-16T10:26:00+08:00
description: use Carbon\Carbon; // Carbon 类在 Carbon 命名空间中声明 // 获取当前时间 echo Carbon::now(); // 2017-04-07 16:32:28 // 今天 echo Carbon::today(); // 2017-04-07 00:00:00 // 明天 echo Carbon::tomorrow(); // 2017-04-08 00:00:00 // 昨天 echo Carbon::yesterday(); // 2017-04-06 00:00:00 // 获取前一天的开始时间 echo Carbon::now()->yesterday()->startOfDay(); // 2017-04-06 00:00:00 // 获取前一天的结束时间 echo Carbon::now()->yesterday()->endOfDay(); // 2017-04-06 23:59:59 //上一周开始时间 (星期一) echo Carbon::now()->previous()->startOfWeek(); // 2017-03-27 00:00:00 // 这周周一 echo Carbon::now()->startOfWeek(); // 2017-04-03 00:00:00 //上一周结束时间 (星期天) echo Carbon::now()->previous()->endOfWeek(); // 2017-04-02 23:59:59 // 这周周天 echo Carbon::now()->endOfWeek(); // 2017-04-09 23:59:59 //获取上一月的开始时间 echo Carbon::now()->subMonth(1)->startOfMonth(); // 2017-03-01 00:00:00 // 获取上一月的结束时间 echo Carbon::now()->subMonth(1)->endOfMonth(); // 2017-03-31 23:59:59 // 这个月的第一天开始时间 echo Carbon::now()->startOfMonth(); // 2017-04-01 00:00:00 // 这个月的最后一天结束时间 echo Carbon::now()->endOfMonth(); // 2017-04-30 23:59:59 // 获取上一年的开始时间 echo Carbon::now()->subYear(1)->startOfYear(); // 2016-01-01 00:00:00 // 今年开始时间 echo Carbon::now()->startOfYear(); // 2017-01-01 00:00:00 echo Carbon::now()->lastOfYear()->startOfYear(); // 2017-01-01 00:00:00 // 获取上一年的结束时间 echo Carbon::now()->subYear(1)->endOfYear(); // 2016-12-31 23:59:59 // 今年结束时间 echo Carbon::now()->endOfYear(); // 2017-12-31 23:59:59 echo Carbon::now()->lastOfYear()->endOfYear(); // 2017-12-31 23:59:59 // 获取当前时间的固定格式 echo Carbon::now()->format('Y-m-d'); // 2017-04-07 // 几号 echo Carbon::now()->day; // 7 // 几月 echo Carbon::now()->month; // 4 // 年 echo Carbon::now()->year; // 2017 // 小时 echo Carbon::now()->hour; // 分钟 echo Carbon::now()->minute; // 上周的今天是星期几 echo Carbon::now()->dayOfWeek; // 5 // 今天是365天中的第几天 echo Carbon::now()->dayOfYear; // 96 // 这个月中的第几周 echo Carbon::now()->weekOfMonth; // 1 // 年中的第几周 echo Carbon::now()->weekOfYear; // 14 // 季度 echo Carbon::now()->quarter; // 2 // 几岁 echo Carbon::createFromDa…

Laravel 8.x新增的AsArrayObject和AsCollection字段映射（casts）
type: item
date: 2023-04-07T16:37:49+08:00
description: 背景： laravel原来可以把数据库中的JSON / TEXT字段转换为array或collection，类似这样：$casts = ['options' => 'array'];但是这个特性，带来很多便利的同时，也有一些不足之处，比如当只是更新array当中某个属性时，很多开发者倾向于这样写:$user = User::find(1); $user->options['foo'] = 'bar'; $user->save();貌似应该起作用的逻辑，在这里却不行，这个经过laravel cast转换出来的array，要更改其中的某个属性，必须对整个array进行操作才行，通常是覆写整个array：$user = User::find(1); $user->options = ['foo' => 'bar']; $user->save();为了解决这个可能误导很多新手的问题，在laravel 8的后期版本，开始引入了AsArrayObject + AsCollection这两个新的cast类型。AsArrayObject通过PHP的ArrayObject来实现，能够以array的常见方式来操作object：// model里定义cast... $casts = ['options' => AsArrayObject::class]; // 具体操作... $user = User::find(1); $user->options['foo']['bar'] = 'baz'; $user->save();需要注意的是，这个时候的ArrayObject ，不能放进常见的array函数里来操作，比如array_map, 这种情况下，你可以通过$user->options->toArray()来获取其背后的原始array，或者也可以通过$user->options->collect()来将其转换为collection实例。基于其新增的便利，所以以后我们再想着cast某个字段为array或者collection的时候，不妨默认cast为AsArrayObject或者AsCollection类型，以后的laravel文档也会重点展示这两个类型的使用。

Release Notes
type: item
date: 2023-04-07T10:40:00+08:00
description: Versioning SchemeSupport PolicyLaravel 10Versioning SchemeLaravel and its other first-party packages follow Semantic Versioning. Major framework releases are released every year (~Q1), while minor and patch releases may be released as often as every week. Minor and patch releases should never contain breaking changes.When referencing the Laravel framework or its components from your application or package, you should always use a version constraint such as ^10.0, since major releases of Laravel do include breaking changes. However, we strive to always ensure you may update to a new major release in one day or less.Named ArgumentsNamed arguments are not covered by Laravel's backwards compatibility guidelines. We may choose to rename function arguments when necessary in order to improve the Laravel codebase. Therefore, using named arguments when calling Laravel methods should be done cautiously and with the understanding that the parameter names may change in the future.Support PolicyFor all Laravel releases, bug fixes are provided for 18 months and security fixes are provided for 2 years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. In addition, please review the database versions supported by Laravel.VersionPHP (*)ReleaseBug Fixes UntilSecurity Fixes Until87.3 - 8.1September 8th, 2020July 26th, 2022January 24th, 202398.0 - 8.2February 8th, 2022August 8th, 2023February 6th, 2024108.1 - 8.2February 14th, 2023August 6th, 2024February 4th, 2025118.2Q1 2024August 5th, 2025February 3rd, 2026End of lifeSecurity fixes only(*) Supported PHP versionsLaravel 10As you may know, Laravel transitioned to yearly releases with the release of Laravel 8. Previously, major versions were released every 6 months. This transition is intended to ease the maintenance burden on the community and challenge our development team to ship amazing, powerful new features without introducing breaking changes. Therefore, we have shipped a variety of…