1. Go to this page and download the library: Download laragear/json library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Before
$name = $json['users'][1]['name'] ?? null;
// After
$name = $json->get('users.1.name');
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');
}
use Laragear\Json\Json;
use Illuminate\Support\Facades\Route;
Route::get('send', fn() => Json::make(['this_is' => 'cool']));
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');
});
use Laragear\Json\Json;
$json = new Json([
'users' => [
'id' => 1,
'name' => 'John',
]
]);
use Laragear\Json\Json;
$json = Json::fromJson('{"users":{"id":1,"name":"John"}}');
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,
];
}
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"