Larravel ` Http:: withUrlParameters ` Usage Author: Chuwen Time: 2023-07-18 Classification: Laravel , PHP comment ##Before use When calling the HTTP API, you will find that many APIs adopt the * REST API * style, for example: * /admin/api/2023-07/products/{product_id}.json * /admin/api/2023-01/orders/{order_id}.json * /admin/api/2023-01/orders/{order_id}/fulfillments/{fulfillment_id}.json * ... It is not difficult to find that they all have one thing in common. They are replaced with corresponding values by variables wrapped in curly braces ('{var_name}', '{order_id}'). Usually, we may do this: ```php $http = \Illuminate\Support\Facades\Http::baseUrl(' https://example.com '); $order_id = 123456789; $fulfillment_id = 9889894445; $orderUrl = sprintf('/admin/api/2023-07/orders/%d.json', $product_id); $fulfillmentUrl = sprintf('/admin/api/2023-01/orders/%d/fulfillments/%d.json', $order_id, $fulfillment_id); $order = $http->get($orderUrl); $fulfillment = $http->get($fulfillmentUrl); ``` However, it will be tedious to splice URIs like this ##After use - ` Http:: withUrlParameters` ```php $http = \Illuminate\Support\Facades\Http::baseUrl(' https://example.com ') ->withUrlParameters([ 'order_id' => 123456789, 'fulfillment_id' => 9889894445 ]); //For example, you need to use the above URL parameter: order_id //You only need to fill in {order_id} in the URL //Automatically replace when requested $orderUrl = '/admin/api/2023-07/orders/{order_id}.json'; $fulfillmentUrl = '/admin/api/2023-01/orders/{orders_id}/fulfillments/{fulfillment_id}.json'; $order = $http->get($orderUrl); $fulfillment = $http->get($fulfillmentUrl); ``` You will find it convenient to use, and you don't need to use "sprintf" to splice URLs
Larravel Model relationships Query does not find a value Return default value Author: Chuwen Time: 2023-05-29 Classification: Laravel comment ##Laravel model association query does not find a value, and the default value is returned In actual business, model association queries are often used, but sometimes the associated model does not exist in the database, and null will be returned. If you judge whether it is null, the logic is complex. Here is a common example in reality Suppose there are two models, 'User:: class' and' UserConfig:: class` **User::class** ```php <? php namespace App\Models; /** * \App\Models\User * * @property int $id * @property string $username * ... Omit some attributes * * @property-read \App\Models\UserConfig|null $config */ class User extends Model { protected $table = "users"; public function config() { return $this->hasOne(\App\Models\UserConfig::class, 'uid', 'id'); } } ``` **UserConfig::class** ```php <? php namespace App\Models; /** * \App\Models\UserConfig * * @property int $id * @property int $uid * @property array $locales * ... Omit some attributes */ class UserConfig extends Model { protected $table = "config"; } ``` Sample code: ```php $uid = 1; $userM = User::findOrFail($uid); return [ //If the associated config model cannot find a value, an error will be reported 'locales' => $userM->config->locales ]; ``` ##Solution [Flipping through documents]( https://laravel.com/docs/10.x/eloquent-relationships#default -Models) found such a method ` withDefault()` Interpretation of official documents: > The belongsTo, hasOne, hasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\Models\User model if no user is attached to the Post model: > >Machine translation into Chinese: > >>If the given relationship is empty, you can define a default model. This mode is usually called 'empty object mode', which can help delete condition checks in code. In the following example, if no user is attached to the Post model, the user relationship will return an empty App Models User model: The usage is simple. Just add the method '->withDefault()' at the end of 'hasOne', and then write the default value in the '$attributes' attribute of' UserConfig:: class' **User::class** ```php <? php namespace App\Models\Admin; /** * \App\Models\User * * @property int $id * @property string $username * ... Omit some attributes * * @property-read \App\Models\UserConfig|null $config */ class User extends Model { protected $table = "users"; public function config() { return $this->hasOne(\App\Models\UserConfig::class, 'uid', 'id')->withDefault(); } } ``` **UserConfig::class** ```php <? php namespace App\Models; /** * \App\Models\UserConfig * * @property int $id * @property int $uid * @property array $locales * ... Omit some attributes */ class UserConfig extends Model { protected $table = "config"; protected $attributes = [ 'locales' => ['en'] ]; } ``` ```php $uid = 1; $userM = User::findOrFail($uid); return [ //If the associated config model cannot find a value, the default value ['en '] will be returned 'locales' => $userM->config->locales ]; ```
Larravel Model (model) implements table splitting query - a certain number of table splitting queries according to UID Author: Chuwen Time: 2023-04-28 Classification: Laravel , PHP comment When the business reaches a certain amount, some tables may need to be divided into tables, databases and other methods to speed up database queries, which can be implemented in Larravel as follows ###The code implementation is as follows ```php <? php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Orders extends Model { protected $table = 'orders'; /** *Get sub table name * * @param int $uid *@ param int $count How many users divide a table? By default, 10000 users divide a table * @return string */ public static function getPartitionedTableName(int $uid, int $count = 10000): string { $tableNum = ceil($uid / $count); return $this->table . "_" . (($tableNum - 1) * $count + 1) . "_" . ($tableNum * $count); } public function scopeByUid($query, int $uid) { return $query->from(self::getPartitionedTableName($uid))->where('uid', $uid); } } ``` ###Usage ```php //The table searched is orders_1_10000 Orders::byUid(4)->first(); //The table searched is orders_10001_20000 Orders::byUid(20000)->first(); ```
Use PHPStorm advanced metadata Author: Chuwen Time: 2023-02-11 Classification: Laravel , PHP comment ##Example 1 You want to get the user model through '$request ->user()', but it's very annoying that there is no type prompt. You can do this Create a file '. phpstrom. meta. php' in the project and path, and then write: ```php <? php // @formatter:off namespace PHPSTORM_META { //Define Output Type override(\Illuminate\Http\Request::user(), map([ '' => \App\Models\User::class, ])); } ``` Then there will be a type prompt: ! []( https://cdn.nowtime.cc/2023/02/10/1231715426.png ) For more advanced usage, see: https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html#map
Laravel obtains relevant values according to the Session ID Author: Chuwen Time: 2022-10-10 Classification: Laravel comment ##Background -Domain name of System A 'admin. xxxx. com' - Dcat Admin, Session authentication is used -A1 System domain name 'api. sass. com' - use JWT authentication Because the project has a requirement, it needs to access the A1 system from the A system. In fact, the A system generates the JWT and transfers it to the A1 system. The JWT format is as follows: >Use the 'sub' mark to mark who generated it, so that the A1 system can judge ! []( https://cdn.nowtime.cc/2022/10/10/3948634876.png ) If you need to log out of System A, the JWT information of System A1 cannot pass the authentication Because the two systems share a set of codes, it is proposed to use the 'Session ID' to write into the JWT 'payload', and then the 'A1 System' gets the 'Session ID' to verify ##Implementation ###Get Laravel Session ID System A obtains a 40 length 'Session ID' through 'Illuminate Support Facades Session:: getId()', generates a JWT, and passes it to System A1 for use ! []( https://cdn.nowtime.cc/2022/10/10/3680874563.png ) ###[A1 System] Verify whether the Session ID exists The example code is as follows: ```php //The actual need here is to parse from JWT and get the 'session_id' field $sessionId = ''; $data = Illuminate\Support\Facades\Session::getHandler()->read($sessionId); if(empty($data)){ //TODO: SessionID does not exist, please check } ```