laragear/json
Composer 安装命令:
composer require laragear/json
包简介
Easily retrieve and manipulate `Json` across your application.
README 文档
README
Easily retrieve and manipulate Json across your application.
use Laragear\Json\Json; $json = Json::fromJson('{"foo":"bar"}'); $json->set('bar.quz', 'quz'); echo $json->foo; // "quz"
Become a sponsor
Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!.
Requirements
- PHP 8.3 or later
- Laravel 12 or later
Installation
Fire up Composer and require this package in your project.
composer require laragear/json
That's it.
Why is this for?
If you feel cumbersome to build complex JSON responses, or to deal with JSON trees values back and forth, this package is for you. It comes with a lot of features to make not only building and manipulating JSON trees.
// Before $name = $json['users'][1]['name'] ?? null; // After $name = $json->get('users.1.name');
From the HTTP Request
Simply use getJson() to automatically retrieve all the JSON from the request, or a given key value.
use Illuminate\Http\Request; use Laragear\Json\Json; public function data(Request $request) { // Get the request JSON. $json = $request->getJson(); // Return a key value from the JSON. $value = $json->get('this.is'); // Set a value and return it. return $json->set('this.is', 'awesome'); }
Tip
You can still use the json() method to retrieve the JSON data as a ParameterBag or a key value.
As an HTTP Response
You can build a Json instance using make(), optionally with your own array, but you can also use anything that implements the Arrayable contract or is iterable. Since the Json instance implements the Responsable trait, you can return it as-is and will be automatically transformed into a JSON response.
use Laragear\Json\Json; use Illuminate\Support\Facades\Route; Route::get('send', fn() => Json::make(['this_is' => 'cool']));
You can also transform it into a response and modify the outgoing response parameters, like the header or the status.
use Laragear\Json\Json; use Illuminate\Support\Facades\Route; Route::get('send', function() { return Json::make(['this_is' => 'cool']) ->toResponse() ->header('Content-Version', '1.0'); });
Creating an instance
If you already have the array you want to transform into JSON, use the make() method or just instantiate it manually. Either way is fine. You can also use Arrayable objects and anything that is iterable, like Collections.
use Laragear\Json\Json; $json = new Json([ 'users' => [ 'id' => 1, 'name' => 'John', ] ]);
If the value is already a JSON string, use fromJson().
use Laragear\Json\Json; $json = Json::fromJson('{"users":{"id":1,"name":"John"}}');
Available methods
The Json instance contains multiple helpful methods to make dealing with JSON data a breeze:
| Method | Description |
|---|---|
get($key, $default = null) |
Retrieves a key value in "dot" notation, returning a default value if its not set. |
getMany([$key => $value], $default = null) |
Retrieves an array of values keyed "dot" notation, filling a default value on those not set. |
set($key, $value, $overwrite = true) |
Sets a key in "dot" notation with a value. |
setMany([$key => $value], $overwrite = true) |
Sets multiple keys in "dot" notation with their respective values. |
fill($key, $value) |
Sets a key in "dot" notation with a value if the key doesn't exists or is null. |
fillMany([$key => $value]) |
Sets multiple keys in "dot" notation with their respective values if they don't exist. |
has($key) |
Check if a key in "dot" notation is defined in the JSON. |
hasAny(...$keys) |
Check if at least one of the keys in "dot" notation is defined in the JSON. |
missing($key) |
Check if a key in "dot" notation is not defined in the JSON. |
forget($key) |
Removes (forgets) a key in "dot" notation from the JSON. |
unset($key) |
Removes (forgets) a key in "dot" notation from the JSON. |
isSet($key) |
Check if a key in "dot" notation exists and is not null. |
isNotSet($key) |
Check if a key in "dot" notation doesn't exists or is not null. |
isEmpty() |
Check if the JSON data is empty. |
isNotEmpty() |
Check if the JSON data is not empty. |
keys() |
Returns an array of all the root-level keys of the JSON. |
only(...$keys) |
Returns an array of only the issued root-level keys of the JSON. |
except(...$keys) |
Returns an array of all the root-level keys of the JSON except those issued. |
segments($keys, $default = null) |
Returns a Json instance a segment of the JSON data using keys in "dot" notation. |
collect($key = null) |
Returns a Collection instance from the JSON data, or value of a key in "dot" notation. |
make($value = []) |
Creates a new Json instance from an iterable or Arrayablevalue. |
wrap($value) |
Returns a Json instance from an iterable or Arrayable value if it's not Json. |
fromJson($string) |
Returns a Json instance from a JSON-encoded string. |
Eloquent JSON Cast
When dealing with JSON attributes in models, you will note that is really cumbersome to work with. Instead of using arrays or Collections, you can use the AsJson and AsEncryptedJson casts, that will offer a Json instance from the model property as-is or encrypted into the database, respectively.
Just add one of these to your model casts.
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laragear\Json\Casts\AsJson; use Laragear\Json\Casts\AsEncryptedJson; class User extends Model { /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'options' => AsJson::class, 'secure_options' => AsEncryptedJson::class, ]; }
Once done, you can easily fill JSON into your model like normal.
use App\Models\User; use Laragear\Json\Json; $user = User::find(); // Set a Json instance, like from a string. $user->options = Json::fromJson('{"apples":"tasty"}') // Or just directly use an array tree. $user->secure_options = [ 'visa' => [ ['last_4' => '1234', 'preferred' => true] ] ]; // You can use the Json instance like a normal monday. $user->secure_options->get('visa.last_4'); // "1234"
PhpStorm stubs
For users of PhpStorm, there is a stub file to aid in macro autocompletion for this package. You can publish them using the phpstorm tag:
php artisan vendor:publish --provider="Laragear\Json\JsonServiceProvider" --tag="phpstorm"
The file gets published into the .stubs folder of your project. You should point your PhpStorm to these stubs.
Laravel Octane compatibility
- There are no singletons using a stale application instance.
- There are no singletons using a stale config instance.
- There are no singletons using a stale request instance.
- There are no static properties written.
There should be no problems using this package with Laravel Octane.
Security
If you discover any security-related issues, please email darkghosthunter@gmail.com instead of using the issue tracker.
License
This specific package version is licensed under the terms of the MIT License, at the time of publishing.
Laravel is a Trademark of Taylor Otwell. Copyright © 2011–2026 Laravel LLC.
laragear/json 适用场景与选型建议
laragear/json 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.22k 次下载、GitHub Stars 达 36, 最近一次更新时间为 2022 年 07 月 05 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「http」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 laragear/json 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 laragear/json 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 laragear/json 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
Get wordpress nav menus and share the main site menus with the child sites.
统计信息
- 总下载量: 4.22k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 36
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-07-05
