Skip to content
/ Json Public

Easily retrieve and manipulate JSON across your application.

License

Notifications You must be signed in to change notification settings

Laragear/Json

Repository files navigation

JSON Transport

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:

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

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