PHP code example of echoaro / laravel-json-mutator
1. Go to this page and download the library: Download echoaro/laravel-json-mutator 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/ */
echoaro / laravel-json-mutator example snippets
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use JsonMutator\Casts\JsonMutatorCast;
class User extends Model
{
protected $casts = [
'metadata' => JsonMutatorCast::class,
];
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use JsonMutator\Casts\JsonMutatorAttributeCast;
class User extends Model
{
protected function metadata(): Attribute
{
return JsonMutatorAttributeCast::make();
}
}
// Create a new user
$user = new User();
// Using array access syntax
$user->metadata['profile']['name'] = 'John Doe';
$user->metadata['profile']['email'] = '[email protected]';
$user->metadata['preferences']['theme'] = 'dark';
// Access metadata using array access
echo $user->metadata['profile']['name']; // Output: John Doe
echo $user->metadata['profile']['email']; // Output: [email protected]
// Using magic properties
$user->metadata->user_role = 'admin';
$user->metadata->last_login = '2024-01-15 10:30:00';
echo $user->metadata->user_role; // Output: admin
echo $user->metadata->last_login; // Output: 2024-01-15 10:30:00
// Using direct array assignment
$user->metadata = [
'profile' => [
'name' => 'John Doe',
'email' => '[email protected]'
],
'preferences' => [
'theme' => 'dark'
]
];
// Save the user
$user->save();
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->json('metadata')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('metadata');
});
}
};