laragear/json

Easily retrieve and manipulate `Json` across your application.

v2.0.0 2024-03-06 22:59 UTC

This package is auto-updated.

Last update: 2024-12-01 00:09:54 UTC


README

Latest Version on Packagist Latest stable test run Codecov coverage CodeClimate Maintainability Sonarcloud Status Laravel Octane Compatibility

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

  • Laravel 10 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 a 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:

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 time of publishing.

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2023 Laravel LLC.